Newbie - React.js - Remove PropTypes and add flow

Hi,
I want to remove PropTypes from my React app.
I have already installed flow.
What is the proper way to replace PropTypes with flow?
Thank you.

import React from 'react'

import smoothscroll from 'smoothscroll-polyfill'
import PropTypes from 'prop-types'

const ScrollTo = props => {
  return props.children
}

class Scroll extends React.Component {
  static propTypes = {
    type: PropTypes.string,
    element: PropTypes.string,
    offset: PropTypes.number,
    timeout: PropTypes.number,
    children: PropTypes.node.isRequired,
  }

  componentDidMount() {
    smoothscroll.polyfill()
  }

  scrollTo = element => {
    const position =
      element && element.getBoundingClientRect().top + window.pageYOffset

    window.scroll({ top: position, left: 0, behavior: 'smooth' })
  }

  handleClick = e => {
    const { element } = this.props
    let scrollToElement
    const el = document.getElementById(element)

    scrollToElement = !!el
    scrollToElement
      ? this.scrollTo(el)
      : console.log(`Element not found: ${el}`)
 
    e.preventDefault()
  }

  render() {
    const { children } = this.props

    return (
      <ScrollTo>
        {typeof children === 'object' ? (
          React.cloneElement(children, { onClick: this.handleClick })
        ) : (
          <span onClick={this.handleClick}>{children}</span>
        )}
      </ScrollTo>
    )
  }
}

export default Scroll

Have you checked the Flow docs? It looks very similar to how you’d do it in Typescript.

import React from 'react';

type Props = {
  foo: number,
  bar?: string,
};

class MyComponent extends React.Component<Props> {
  render() {
    this.props.doesNotExist; // Error! You did not define a `doesNotExist` prop.

    return <div>{this.props.bar}</div>;
  }
}

<MyComponent foo={42} />;
2 Likes

So silly, I’m really sorry for asking. I didn’t search as I should search. :wink:
Thank you anyway.

1 Like

Np.

I’m not sure why you’ve chosen Flow, but TS seems to have better adoption and is included in the latest create-react-app and in Babel 7. I’ve been on it for a few months now and am loving it. The Flow from the docs that posted looks very similar.

Typescript version:

import React from 'react'

interface Props {
  foo: number
  bar?: string
}

class MyComponent extends React.Component<Props> {
  render() {
    this.props.doesNotExist; // Error! You did not define a `doesNotExist` prop.

    return <div>{this.props.bar}</div>;
  }
}

<MyComponent foo={42} />;

Thank you for recommendation I’m gonna use it in near future. ; )

1 Like

Also, I ran into these again after you posted this thread. I feel like Flow’s days are numbered. Both Jest and Yarn are moving off of it to Typescript, 2 very major FB projects.

1 Like

Great tips and articles.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.