React Components

Prefer stateless components

You should start with a stateless component. Upgrade to a Class only if State becomes absolutely necessary.

import React from 'react'
import './styles.css'

const UserGreeting = props => (
  <div>
    <h1>Hello</h1>
    <h1 className='name'>{props.name}</h1>
  </div>
)

export default UserGreeting

When to use class components

Class Components are usually used as parent containers to provide your subcomponents with data. Use them only if you need State.

import React, { Component } from 'react'

import './styles.css'

// If empty, this component should be Stateless
const initialState = {
  name: 'John'
}

class UserGreeting extends Component {
  state = initialState

  render() {
    return (
      <div>
        <h1>Hello</h1>
        <h1 className='name'>{this.state.name}</h1>
      </div>
    )
  }
}

export default UserGreeting

Use props.children for template components

If you find yourself needing to wrap elements inside of a component, you can use props.children which contains all the elements wrapped inside the component tag. A few use cases would be for Modals, Dialogs, and Cards.

import React from 'react'

const MyApp = () => <UserGreeting>Johnny</UserGreeting>
export default MyApp
import React from 'react'
import './styles.css'

const UserGreeting = props => (
  <div>
    <h1>Hello</h1>
    <h1 className='name'>{props.children}</h1>
  </div>
)

export default UserGreeting

Use defaultProps to make reusable components

We like using defaultProps because we can make reusable components to make certain constants overridable. Both Stateless/Stateful Components can use DefaultProps however it's best you only use it on Stateless Components.

import React from 'react'

import './styles.css'

const UserGreeting = props => (
  <div>
    <h1>Hello</h1>
    <h1 className='name'>{props.name}</h1>
  </div>
)

UserGreeting.defaultProps = {
  name: 'John'
}

export default UserGreeting

Your components won't break when props are missing.

    <UserGreeting name={'Joe'} />
    <UserGreeting /> // No props, no problem

Additional guidelines

// Keep External Libraries on Top
// Use Named Imports for additional Methods/Components
import React, { Component, Fragment } from 'react'
// Right after are your own files such as Styles/SubComponents/Helpers/Types/etc.
import './styles.css'
// If empty, this component should be Stateless
const initialState = {
  name: 'John'
}
// Component Names must be in Pascal Case and Unique,
// No Two Components should have the same Name across your entire App.
class UserGreeting extends Component {
  state = initialState

  render() {
    return (
      // Multiple elements needs to be wrapped in a Fragment or Div
      <Fragment>
        <h1>Hello</h1>
        <h1 className='name'>{this.state.name}</h1>
      </Fragment>
    )
  }
}

export default UserGreeting

References