Skip to content

Instantly share code, notes, and snippets.

@ethan-deng
Last active November 4, 2015 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ethan-deng/41c8ccd51a8fbf4baaec to your computer and use it in GitHub Desktop.
Save ethan-deng/41c8ccd51a8fbf4baaec to your computer and use it in GitHub Desktop.

React Props, State and Data Flow

In React always treat component props and state as immutable. props are owned by parent component and flow one-way from parent to child. State is private to the current component and can only be changed by setState. When there is need to flow data from child to parent, use the event handler.

  1. Don't try to access children component's state using refs.

For example (bad code)

this.refs.myChildComp.state

Instead (good code)

Use event handler

<button type="button" className="btn btn-primary" data-dismiss="modal" onClick={this.props.onOK.bind(self, self.state.entityName, self.state.entityUniqueName>Ok</button>
  1. Don't try to set child component's prop using refs

For exmaple (bad code)

this.refs.myChildComp.props.myProp = "hello";

Instead (good code)

Set the child component's props to state and change the state by calling setState

<span data-uniquename={this.state.uniquename}>{this.state.name + ','}</span>

As a rule of thumb, never use refs to access child component's props or state from a parent component. For example, the child component's props should be known by parent already. Usually it is based on parent component's state. State is owned by the child component and private to child component.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment