0
Hello, I’m initiating the studies in React and when trying to create a code that generates components (in this case the "Box")where at the click of a button passing objects coming from a state to a props, party of a form, always gives Undefined value error:
The error occurs when trying to compile the following code:
const [name, setName] = useState('')
const [email, setEmail] = useState('')
const [salario, setSalario] = useState('')
const [ box,setBox] = useState([{nome:"name", mail:"email", sal:"salario"}])
function handleGenerate(){
setBox([...box, {name, email, salario} ])
setName('');
setEmail('');
setSalario('');
const handleChangeName= (event)=>{setName(event.target.value)}
const handleChangeEmail= (event)=>{setEmail(event.target.value)}
const handleChangeSalario= (event)=>{setSalario(event.target.value)}
return(
<React.Fragment>
<input type="text" placeholder="Nome" value ={name} onChange={text => handleChangeName(text)}/><br/>
<input type="text" placeholder="email" value ={email} onChange={text => handleChangeEmail(text)} /><br/>
<input type="text" placeholder="salario" value ={salario} onChange={text => handleChangeSalario(text)} /><br/>
<button onClick={handleGenerate}>Gerar box</button>
{box.map((box, index)=>{
return <Box key={index} index={index} name = {box[index].nome} email ={box[index].mail} salario ={box[index].sal}/>
})
}
</React.Fragment>
)
}
function Box(props){
return(
<div id="box">
<h2>Funcionario</h2>
<h3>nome = {props.name}</h3>
<h3>email = {props.email}</h3>
<h3>salario = {props.salario}</h3>
<h3>index = {props.index} </h3>
</div>
)
}
It is important to note that each Box has to come according to the items that were placed in the inputs at the instant I click the button.
Thanks in advance and sorry for any mistake :)
Remove all the
[index]
of this passage:return <Box key={index} index={index} name = {box[index].nome} email ={box[index].mail} salario ={box[index].sal}/>
– bfavaretto
But when I take the index no value is passed to the Box (only Undefined)
– Gabriel Barbosa
That’s how you left it?
return <Box key={index} index={index} name = {box.nome} email ={box.mail} salario ={box.sal}/>
?– bfavaretto
yes. I had even tested it like this before, but it happens like I said
– Gabriel Barbosa