“Functions are not valid as a React child” error is a common issue that developers encounter when working with React. This error occurs for two main reasons: returning a function reference and not a component from render, and using React Router routes incorrectly.
Reason 1: Returning a function instead of JSX
One of the main causes of this error is when developers return a function reference and not a component from render. Here’s a simple example of how this error occurs:
App.js/** * Functions are not valid as a React child. */const App = () => { const getButton = () => { return <button>Click</button>; }; // returning function and not JSX element from render return <div>{getButton}</div>;};export default App;
Solution 1: Call the function
To solve this error, you can call the function instead of returning the function reference.
App.jsconst App = () => { const getButton = () => { return <button>Click</button>; }; // now returning the actual button // added parentheses () to call the function return <div>{getButton()}</div>;};export default App;
Reason 2: Using React Router routes incorrectly
Another common cause of this error is when we pass an element to a React Router route like . This is incorrect syntax, and the correct syntax should be } />.
Solution 2: Render the component
When using React Router, make sure to pass the component that should be rendered for the specific route as and not Component.
App.js// wrong syntax<Route path="/about" element={About} />// right syntax<Route path="/about" element={<About />} />
Conclusion on “Functions are not valid as a React child error”
In summary, the “Functions are not valid as a React child” error can occur for two main reasons: returning a function reference and not a component from render, and using React Router routes incorrectly.
To solve this error, you can call the function instead of returning the function reference, or make sure to pass the component that should be rendered for the specific route as and not Component when using React Router. functions are not valid as react child.
Comments
Post a Comment