Home > OS >  Error when populating dropdown only after refresh page
Error when populating dropdown only after refresh page

Time:08-22

I'm trying to populate a dropdown with a set array colors. When I load it the first time, the dropdown is populated and it works. When I refresh the page, I get an error..

My App.js looks like this:

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 >

        <select onChange={handleChange}  class ="form-control" name="" id="color">

        </select>
      </div>
      
    </div> 
  );
}

export default App;

The error I get when I refresh is:

    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.

I'm very new to JavaScript, but my thought is that maybe it needs to clear the element first or something? Not sure, because I just followed a tutorial and I never see anything added..

CodePudding user response:

You have to read the react basics. Go to https://reactjs.org/tutorial/tutorial.html

A way to do it would be like this:

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;
  • Related