Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Variables in setState in JSX

I would like to use a variable in the setState function in a JSX file for React.

How would I restructure this code:

var name = e.target.name;
if(name == "title"){
    this.setState({ title: e.target.value});
}
else if(name == "date"){
    this.setState({ date: e.target.value});
}
else if(name == "amount"){
    this.setState({ amount: e.target.value});
}

Into something like this (so I don't repeat myself)?

var name = e.target.name;
this.setState({ name: e.target.value});

The above syntax just sets the state of "name" and not the value of the "name" variable.

like image 277
sifxtreme Avatar asked Jun 01 '15 00:06

sifxtreme


People also ask

Can we declare a variable in JSX?

In the example below, we declare a variable called name and then use it inside JSX by wrapping it in curly braces: const name = 'Josh Perez';const element = <h1>Hello, {name}</h1>; You can put any valid JavaScript expression inside the curly braces in JSX.

How do you set state variables in React?

import React, { useState } from 'react'; function Example() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0); We declare a state variable called count , and set it to 0 .

How do you pass state value to another functional component React?

Sending state/props to another component using the onClick event: So first we store the state/props into the parent component i.e in which component where we trigger the onClick event. Then to pass the state into another component, we simply pass it as a prop.

Can we use setState in shouldComponentUpdate?

shouldComponentUpdate() Safe to use setState ? Yes! This method is called whenever there is an update in the props or state. This method has arguments called nextProps and nextState can be compared with current props and currentState .


2 Answers

Easy:

var newState = {};
newState[e.target.name] = e.target.value;
this.setState(newState);
like image 124
Alex McMillan Avatar answered Oct 16 '22 22:10

Alex McMillan


var update = {};
update[e.target.name] = e.target.value;
this.setState(update);

If you're using an ES6 transpliler that supports computed property names (like Babel), you can do:

this.setState({[e.target.name]: e.target.value});
like image 5
Michelle Tilley Avatar answered Oct 16 '22 21:10

Michelle Tilley