Shweta Singh Shweta Singh - 1 year ago 81
React JSX Question

Want to know more about Props & State

I tried reading books and watching videos about JS and React, but still I don't have better understanding of React-Props & States.
Can some one please explain me in details.

Answer Source

Props Components Props can be thought of as a component's options. They're given as arguments to a component and look exactly like HTML attributes.

It's worth noting that a component should never change its props, they're immutable. If a component has data that's mutable, use the state object.

var Photo = React.createClass({
  render: function() {
    return (
      <div className='photo'>
        <img src={this.props.src} />
        <span>{this.props.caption}</span>
      </div>
    );
  }
});

React.render(<Photo src='http://example.com/lkevsb9' caption='Hong Kong!' />, document.body);

State The state object is internal to a component. It holds data which can change over time.

Before we can use state, we need to declare a default set of values for the initial state. This is done by defining a method called getInitialState() and returning an object.

State is set using the setState method. Calling setState triggers UI updates. Setting state should only be done from inside the component.

var InterfaceComponent = React.createClass({
  getInitialState : function() {
    return {
      name : "chris"
    };
  },
  handleClick : function() {
    this.setState({
      name : "bob"
    });
  },
  render : function() {
    return <div onClick={this.handleClick}>
      hello {this.state.name}
    </div>;
  }
});

React.renderComponent(
  <InterfaceComponent />,
  document.body
); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download