When working with ReactJS, managing state is a fundamental aspect of building dynamic and interactive user interfaces. In some cases, you may encounter situations where you need to set state with a dynamic key name, rather than a fixed one. This can be particularly useful when dealing with dynamic data or when you want to update state based on user input or other dynamic factors. In this article, we will explore how to set state with a dynamic key name in ReactJS, allowing you to create more flexible and adaptable components.
Let us create a React project and then we will create a state with a dynamic key name.
Creating React Project:
Step 1: Create a react application by typing the following command in the terminal.
npx create-react-app project_name
Step 2: Now, go to the project folder i.e project_name by running the following command.
cd project_name
Project Structure: It will look like the following:
Example: Let us create an input field that takes the state name as input and state value as another input. Now a button is added which has an onclick function. It creates the state with a dynamic key name enclosing value inside this ‘[ ]’ on a user click. Users can click on the button to create a new state and it will display the newly created state in the UI.
Filename: App.js
Javascript
import React, { Component } from "react" ; class App extends Component { constructor() { super (); this .state = { name: "" , value: " " , }; } render() { return ( <div> <p>Enter State Name:</p> <input onChange={(e) => { this .setState({ name: e.target.value }); }} type= "text" ></input> <p>Enter State Value:</p> <input onChange={(e) => { this .setState({ value: e.target.value }); }} type= "text" ></input> <br /> <br /> <button onClick={() => { this .setState({ [ this .state.name]: this .state.value, }); }} > Create a dynamic state </button> { this .state[ this .state.name] ? ( <p> { this .state.name}:{ this .state[ this .state.name]} </p> ) : null } </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: Open your browser. It will by default open a tab with localhost running and you can see the output shown in the image. Fill in the required details and click on the button. As you can see in the output new state with a dynamic name is created with the value you entered.UI checks if the state exists and then displays the value.