Updating state values using props.
We set up an array of strings testTopics as props for our component. A function listOfTopics is created to map all the strings as list items in our state topics. The function updateState gets triggered and sets the topics to list items. When we click on the button, we get updated state values. This method is well-known for handling complex data and updating the state very easily.
Javascript
// Filename - App.js import React, { Component } from "react" ; class App extends Component { static defaultProps = { testTopics: [ "React JS" , "Node JS" , "Compound components" , "Lifecycle Methods" , "Event Handlers" , "Router" , "React Hooks" , "Redux" , "Context" , ], }; constructor(props) { super (props); // Set initial state this .state = { testName: "React js Test" , topics: "" , }; // Binding this keyword this .updateState = this .updateState.bind( this ); } listOfTopics() { return ( <ul> { this .props.testTopics.map((topic) => ( <li>{topic}</li> ))} </ul> ); } updateState() { // Changing state this .setState({ testName: "Test topics are:" , topics: this .listOfTopics(), }); } render() { return ( <div> <h2>Test Information</h2> <p>{ this .state.testName}</p> <p>{ this .state.topics}</p> { /* Set click handler */ } <button onClick={ this .updateState}> Click me! </button> </div> ); } } export default App; |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
ReactJS setState()
All the React components can have a state associated with them. The state of a component can change either due to a response to an action performed by the user or an event triggered by the system. Whenever the state changes, React re-renders the component to the browser. Before updating the value of the state, we need to build an initial state setup. Once we are done with it, we use the setState() method to change the state object. It ensures that the component has been updated and calls for re-rendering of the component.
Table of Content
- React JS setState
- Steps to Create React Application:
- Updating multiple attributes
- Updating state values using props.
- Updating the state using its previous value.
Contact Us