Issue
Basically, every time that the teachers variable update, I want to it be added to the select tag. My code right now:
const typeOfCreation = [
{
id: 0,
name: 'teachers'
}
]
const [teachers, setTeachers] = useState([])
const createData = () => {
const inputValueTeachers = document.getElementById('teachers')
if (inputValueTeachers?.value == undefined || inputValueTeachers?.value == '') {
break;
}
let oldTeachers = teachers
oldTeachers.push(inputValueTeachers?.value)
setTeachers(oldTeachers)
{typeOfCreation.map((creation) => {
return (
<div key={creation.id} className={'inputsCreation'}>
Creation of {creation.name}<br/>
<input type="text" name="" id={creation.name} /><br/>
<button onClick={_=>createData(creation.name)}>Create</button>
</div>
)
})}
<select name="" id="66">
{teachers.map(teacher => {
return (
<option key={teacher} value={teacher}>{teacher}</option>
)
})}
</select>
The input doesn't dynamic updates, only after the "small reaload" that react does when you save your project the select html input show me the teachers
pls help
Solution
you update the teachers
state incorrectly. it should be like this:
let oldTeachers = [...teachers]
oldTeachers.push(inputValueTeachers?.value)
setTeachers(oldTeachers)
or
setTeachers(p => [...p, inputValueTeachers?.value]);
learn more: Correct modification of state arrays in React.js
Answered By - Layhout
Answer Checked By - - David Goodson (ReactFix Volunteer)