Estoy tratando de completar un menú desplegable con una matriz de colors establecida. Cuando lo cargo por primera vez, el menú desplegable se rellena y funciona. Cuando actualizo la página, me sale un error..
Mi App.js se ve así:
import './App.css'; import React, { useState } from "react"; function App() { var color = ["green","blue"]; var option = ""; for (var i = 0; i < color.length; i ++) { option += '<option value="'+ color[i] + '">' + color[i] + "</option>" } document.getElementById('color').innerHTML = option const handleChange = event => { console.log(event.target.value); }; return ( <div className="App"> <div class="form-group"> <select onChange={handleChange} class ="form-control" name="" id="color"> </select> </div> </div> ); } export default App;El error que me sale cuando actualizo es:
App.js:23 Uncaught TypeError: Cannot set properties of null (setting 'innerHTML') at App (App.js:23:1) at renderWithHooks (react-dom.development.js:16305:1) at mountIndeterminateComponent (react-dom.development.js:20074:1) at beginWork (react-dom.development.js:21587:1) at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1) at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1) at invokeGuardedCallback (react-dom.development.js:4277:1) at beginWork$1 (react-dom.development.js:27451:1) at performUnitOfWork (react-dom.development.js:26557:1) at workLoopSync (react-dom.development.js:26466:1) react-dom.development.js:18687 The above error occurred in the <App> component: at App (http://localhost:3000/static/js/bundle.js:44:46) Consider adding an error boundary to your tree to customize error handling behavior. Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.Soy muy nuevo en JavaScript, pero creo que tal vez primero deba borrar el elemento o algo así. No estoy seguro, porque acabo de seguir un tutorial y nunca veo nada agregado.
Tienes que leer los conceptos básicos de reacción. Vaya a https://reactjs.org/tutorial/tutorial.html
Una forma de hacerlo sería así:
const colors = ["green","blue"]; function App() { const handleChange = event => { console.log(event.target.value); }; return ( <div className="App"> <div className="form-group"> <select onChange={handleChange} className="form-control" name="" id="color"> {colors.map((color, idx) => <option value={color} key={idx}>{color}</option>)} </select> </div> </div> ); } export default App;