Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to set state with a dynamic key name in ReactJS ?

  • Difficulty Level : Easy
  • Last Updated : 27 Oct, 2021

React.js introduces the concept of state. The states are used to store data for specific components. These states can be updated accordingly using setState function. Updation of state leads to rerendering of UI. You can assign meaningful names to states. There can be a requirement to create a state with a dynamic key name. We can do this in React. 

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:

Project Structure

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :