React — Props & State

React uses components to build websites. Props and state are properties of those components. Furthermore, components return one element in their render method. These properties are used to build and/or manipulate the element they are tied to, i.e. the one that is returned.

Props are immutable — they don’t change. State, on the other hand, can change. Components can set their own state with this.setState(). Everytime setState is invoked React re-renders the element that that component is tied to.

Moreover, child components can also inherit properties through React.render() or from their parent component. This inherited property is accessible via this.props. Below is an example of a countdown timer that inherits through React.render().

At line 25 we are passing CountdownTimer this.props.timer = 100. This is done by setting timer= “100” within the <> that the component CountdownTimer is within.

We are then using getInitialState() to set the initial state of our timer to 100. We also have a click handler on our span element which holds the timer. When the span is clicked, handleClick is invoked which then invokes our setInterval. Our setInterval decrements this.state.timer by 1 every 1000 milliseconds.

Here we can see that though we are indirectly changing this.props.timer, what actually changes is this.state.timer. This.props.timer remains 100.

Another way to set this.props is in the parent component. See below:

React allows for nesting components within one another. Within our Playlist component we are rendering the Tracks component. We are also setting the value of the ‘tracks’ property of our child component to the this.state.tracks property of the Playlist component, i.e. the parent component. The ‘tracks’ property is then accessible by our child component through this.props.tracks.