• Xander Stevenson

React.js - Props and State: the Basics


Image credit: https://medium.com/@cgcrutch18/stateful-vs-stateless-react-components-13f647f7fc4


Props


In the React library for JavaScript, we use props as a means to send data to the different components of an app. I like to think of a prop as an immutable (unchangeable) variable that can be shared among the different components, or files, that comprise an app. Every component in React is treated as a pure JavaScript function and props are the equivalent to the parameters / arguments of those functions. In order to share props among components, they are inherently, by convention, exported from each component but, on the other hand, must be explicitly imported. To invoke a prop, and have access to its value, a this is required: this.props.<prop name>


Here's an example of how props is used to render the Food function three times within the App component, which is then rendered to the Document Object Model, or DOM.:


function Eat(props) {

return <h1>I like to eat {props.food}</h1>;

}


function App() {

return (

<div>

<Eat food="Sara" />

<Eat food="Cahal" />

<Eat food="Edite" />

</div>

);

}


ReactDOM.render(

<App />,

document.getElementById('root')

);



State


The state is the data store for each React.js component and, unlike props, can be manipulated. I like to think of state as a variable confined to a single component. The state is most often used to update the component in reaction to an event, such as a click, submit, or text input. Changing the state directly, this.state = {'key': value} , is prohibited but must be performed using setState, this.setState({key: value}).


- State variables are initially assigned at the top of a component, either through a constructor:


class Time extends React.Component {

constructor(props) {

super(props);

this.state = {

date: new Date()

};

}


- or via the direct assignment


state = {

date: new Date()

};


However, as mentioned in the previous paragraph, a state can only be changed by using the setState. The best way to change state is with an ES6 arrow function and the previous state and props as arguments, as such:


this.setState((state, props) => ({

count: state.count + props.increment

}));


Happy Coding!

Xander Stevenson's

  • linkedin logo
  • github logo