0

I am getting into React and I can not find out, how we should define React components.

Should we use ES6 class definition like following:

import React from 'react'
import PropTypes from 'prop-types'

class DateFormatter extends React.Component {
  constructor (props) {
    super(props)
    this.date = props.date
  }
  render () {
    return (<h2>It is {this.date.toLocaleTimeString()}.</h2>
    )
  }
}
DateFormatter.propTypes = {
  date: PropTypes.object
}

export default DateFormatter

or do it like following:

export const DateFormatter = ({ date }) => (
  <div>
    <h2>It is {date.toLocaleTimeString()}</h2>
  </div>
)
DateFormatter.propTypes = {
  date: PropTypes.object
};

export default DateFormatter

Both ways presented above are working properly but I can not get what is the main difference (except semantical)? I know that in second case we create immutable component as it is defined as "const".

2 Answers2

0
export const DateFormatter = ({ date }) => (
  <div>
    <h2>It is {date.toLocaleTimeString()}</h2>
  </div>
)
DateFormatter.propTypes = {
  date: PropTypes.object
};

export default DateFormatter

This is a functional component. It has no state. It just renders the data it is fed with (via props).

import React from 'react'
import PropTypes from 'prop-types'

class DateFormatter extends React.Component {
  constructor (props) {
    super(props)
    this.date = props.date
  }
  render () {
    return (<h2>It is {this.date.toLocaleTimeString()}.</h2>
    )
  }
}
DateFormatter.propTypes = {
  date: PropTypes.object
}

export default DateFormatter

This is a class component. It has a state and is generally more complex than functional components.

Generally, you would have a few class components at the top of your component hierarchy. The more you go down the more you will find functional components. They render the data passed down from the class components.

Julien Klepatch
  • 338
  • 1
  • 5
0

Yes it is duplicated post, but for final clarification this notation is functional notation:

export const DateFormatter = ({ date }) => (
  <div>
    <h2>It is {date.toLocaleTimeString()}</h2>
  </div>
)
DateFormatter.propTypes = {
  date: PropTypes.object
};

export default DateFormatter

and is equal with following:

var DateFormatter = function({date}) {
  return <div><h2>It is {date.toLocaleTimeString()}</h2></div>;
}

DateFormatter.propTypes = {
  date: PropTypes.object
};

export default DateFormatter