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.
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.
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 .
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.
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 .
Easy:
var newState = {};
newState[e.target.name] = e.target.value;
this.setState(newState);
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With