Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a select input dynamic react

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading