0

I came accross 2 ways of declaring components in ReactJs. What is the different as both seem to work fine!

Case I:

function Roger(props){
    return <h1>Hello! {props.name},{props.message}</h1>;
}

Case II:

var Roger = React.createClass({
  render: function() {
    return (
      <h1>Hello! {props.name},{props.message}</h1>
    );
  }
});

Can anyone help me out in understanding difference?

Deadpool
  • 7,811
  • 9
  • 44
  • 88
  • Check the stackoverflow doc for more detail on `Stateless Functional Component`, it will cove all the points in detail: http://stackoverflow.com/documentation/reactjs/6588/stateless-functional-components#t=201704200855545376703 – Mayank Shukla Apr 20 '17 at 08:56

1 Answers1

1

Case I is creating Stateless Functional Components, as a rule of thumb it's recommended to use it whenever possible. Case II is useful for example if you need to use this or if you need life-cycle methods.

Check this great post to learn more: http://jamesknelson.com/should-i-use-react-createclass-es6-classes-or-stateless-functional-components/

From the official docs:

The simplest way to define a component is to write a JavaScript function:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

This function is a valid React component because it accepts a single "props" object argument with data and returns a React element. We call such components "functional" because they are literally JavaScript functions.

You can also use an ES6 class to define a component:

class Welcome extends React.Component {   
  render() {
    return <h1>Hello, {this.props.name}</h1>;   
  } 
}

The above two components are equivalent from React's point of view.

Classes have some additional features that we will discuss in the next sections. Until then, we will use functional components for their conciseness.

source: https://facebook.github.io/react/docs/components-and-props.html#functional-and-class-components

Moe
  • 3,467
  • 1
  • 19
  • 25