Use Case : You get the following error message : react-dom.development.js:61 Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.

Test platform : Windows 10, Chrome, React 17

Exemple of Source code :

<html>
  <body>
    <div id="app">

     <script src="https://unpkg.com/react@17/umd/react.development.js"></script> 
     <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
     <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

     <script type="text/jsx">

	function Header({ title }) {
	  return <h1>{title ? title:'default title'}</h1>;
	}


        function MyPage() {
	  const names = ['John Doe', 'Henri Dust', 'Elton Muk'];

	  return (
	          <div>
	            <Header title="Test list of names" />
		    <ul>
		      {names.map((name) => (
			 <li>{name}</li>
		       ))}
		    </ul>
	          </div>
	   );
	}

		
	ReactDOM.render(<MyPage />, app);

      </script>    	
    </div>
  </body>
</html>


Solution : The line which give the warning is this one :

          {names.map((name) => (
         <li>{name}</li>
           ))}

In this example , for solving the problem you need add a key property to the tag <li>. Aditionally the value of the key property need to be unique like an Id. In your example we will use the index of the item in the array :

<ul>
  {names.map((name) => (
    <li key={names.indexOf(name)}>{name} + - index: ' + {names.indexOf(name)}</li>
   ))}
</ul>

This is because React needs something to uniquely identify an item in the array so React knows which elements to update in the DOM.

Annexe

Full error message

react.development.js:245 Warning: Each child in a list should have a unique « key » prop.

Check the render method of HomePage. See https://reactjs.org/link/warning-keys for more information.
at li
at HomePage

Laisser un commentaire