I have 4 inputs that update a react state when there is text typed inside, only one of them tends to update for some reason and I can’t find out why, there are no typing errors and I have checked the imports, state names, and inputs to make sure that they work correctly. Is there another factor that I’m missing here? thanks in advance
import React, {useState, useEffect} from "react";
export default function Home() {
const [a, setA] = useState()
const [b, setB] = useState()
const [c, setC] = useState()
const [d, setD] = useState()
return (
<>
<input onChange={(e) => setA(e.target.value)} />
<input onChange={(e) => setB(e.target.value)} />
<input onChange={(e) => setC(e.target.value)} />
<input onChange={(e) => setD(e.target.value)} />
<p style={{color:'white'}}>
{a, b, c, d}
</p>
</>
);
}
I have tried changing the state names to different things, I have retyped all inputs manually multiple times, and I have checked the imports to make sure they work. I have also tried having the states start with (‘ ‘) or (), but both didn’t work.
3
Answers
Setting the state works just fine. You have an other mistake:
You should name the properties separately to display them i.e.
{a}, {b}, {c}, {d}
also I had to set the color to black to display the text against a white (default) background.
Writing as
{a, b, c, d}
is giving an error in codesandbox.io:This only displays the last input, where you are updating
d
‘s state. If you would like to display them comma separated, do this:{a}, {b}, {c}, {d}
.Your code looks pretty much correct, I believe the problem is the way you try to print the a,b,c,d variables. When you write a JSX expression (everything starting from the
<>
to the</>
is jsx) what you put within the curly brackets should be a valid javascript expression, it can be a string, a number or many other things. The{a, b, c, d}
probably does not evaluate in the way you think it is, it you want to have it displayed as strings you can write it as:Which is a valid JS code that evaluate to a string that contains a,b,c,d with comma separation.