Functional Components

Based on article

propTypes

Assign the propTypes variable at the top of the file so it's easily viewable to the developer.

Two Ways to do this:

  1. If you use a function for your stateless component, you could take advantage of Javascript function hoisting and do the following:

    Hoisting is JavaScript's default behavior of moving declarations to the top.

    import React from 'react'
    import {observer} from 'mobx-react'
    import './styles/Form.css'
    
    ExpandableForm.propTypes = {
     onSubmit: React.PropTypes.func.isRequired,
     expanded: React.PropTypes.bool
    }
    
    // Component declaration
    function ExpandableForm({ onSubmit, expanded = false, children }) {
    ...
    }
    
  2. If you prefer to use anonymous functions for your stateless component, do the following:

    import React from 'react'
    import {observer} from 'mobx-react'
    import './styles/Form.css'
    
    const propTypes = {
     onSubmit: React.PropTypes.func.isRequired,
     expanded: React.PropTypes.bool
    }
    
    // Component declaration
    const ExpandableForm = ({ onSubmit, expanded = false, children }) => {
    ...
    }
    
    ExpandableForm.propTypes = propTypes
    

Avoid the second option as the function here is unnamed. This lack of name will not be a problem if your Babel is set up correctly — but if it’s not, any errors will show up as occurring in <> which is terrible for debugging.

Destructuring Props and defaultProps

Destructure your props and use default arguments as defaultProps.

import {observer} from 'mobx-react'
import './styles/Form.css'

ExpandableForm.propTypes = {
  onSubmit: React.PropTypes.func.isRequired,
  expanded: React.PropTypes.bool
}
function ExpandableForm({ onSubmit, expanded = false, children }) {
  return (
    <form style={ expanded ? { height: 'auto' } : { height: 0 } }>
      {children}
      <button onClick={onExpand}>Expand</button>
    </form>
  )
}

results matching ""

    No results matching ""