How to set state with a dynamic key name in ReactJS ?
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.
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.
Step to Run Application: Run the application using the following command from the root directory of the project:
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.