Here I have used object and I want to access its name and value and value. This is my code right now..
Here I have used object and in return code I have described name and value now I want to access value and name in my handleChange function tried several ways it is not working.
const [location, setLocation] = React.useState({
lifeLabs: "",
gamma: "",
hamilton: "",
joseph: "",
other:"",
});
const handleChange = (e) => {
const { location } = e.target;
setLocation(location);
};
Here I tried changing the handleChange function using if statement but it did not work.
And this is the return code here I want to access its name and value.
<FormControlLabel
value="Life Labs"
name="lifeLabs"
control={<Radio onChange={handleChange} />}
label="Life Labs"
/>
<FormControlLabel
value="Gamma"
name="gamma"
control={<Radio onChange={handleChange} />}
label="Gamma Dyna-care"
/>
<FormControlLabel
value="Hamilton"
name="hamilton"
control={<Radio onChange={handleChange} />}
label="Hamilton Health Science"
/>
<FormControlLabel
value="Joseph"
name="joseph"
control={<Radio onChange={handleChange} />}
label="St Joseph"
/>
<FormControlLabel
value="Other"
name="other"
control={<Radio onChange={handleChange} />}
label="Other"
/>
CodePudding user response:
I think you should use e.target.value
const handleChange = (e) => {
const { location } = e.target.value;
setLocation(location);
};
CodePudding user response:
You can write it like this
const handleChange = (e) => {
const { name, value } = e.target;
setLocation({ location, [name]: value });
};
CodePudding user response:
In your handleChange
function, you are destructuring location
from e.target
object. But e.target
is radio button itself and does not contain location
property. Instead location
is present on value
or name
subproperty of e.target
.
By looking at your code it seems like your FormControlLabel
and state, appropriate way to set location might be
const handleChange = (e) => {
const { name, value } = e.target;
setLocation({ ...location, [name]: value});
};
- As setState is immutable, we can't update the state, so we use spread operator to retain previous values of location object
- For
[name]: value
, In Javascript, when you create an object literal {} and you wrap the object’s key in array brackets [key] you can dynamically set that key. For reference - https://medium.com/@bretdoucette/understanding-this-setstate-name-value-a5ef7b4ea2b4