Functions are not valid as a React child error

avatar

Borislav Hadzhiev

Last updated: Apr 17, 2022

banner

Photo from Unsplash

Functions are not valid as a React child error #

The error "Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render." occurs for 2 common reasons:

  1. Returning a function reference and not a component from render.
  2. Using react router routes as <Route path="/about" element={About} /> instead of <Route path="/about" element={<About />} />.

functions are not valid as react child

Here is a simple example of how the error occurs.

App.js
/** * ⛔️ Functions are not valid as a React child. * This may happen if you return a Component instead of <Component /> from render. * Or maybe you meant to call this function rather than return it. */ const App = () => { const getButton = () => { return <button>Click</button>; }; // 👇️ returning function not JSX element from render return <div>{getButton}</div>; }; export default App;

The issue in the code snippet is that we are returning the getButton function from our render method instead of returning an actual JSX element.

To solve the error in this scenario, we can call the function.

App.js
const 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;

By calling the getButton function, we return the button element which solves the error.

If you are trying to render an actual component, make sure to use it as <Component /> and not Component.

App.tsx
const App = () => { const Button = () => { return <button>Click</button>; }; // ✅ Using component as <Button />, not Button return ( <div> <Button /> </div> ); }; export default App;

Another common cause of the "Functions are not valid as a React child" error is when we pass an element to a react router route like <Route path="/about" element={About} />.

App.js
// ⛔️ wrong syntax <Route path="/about" element={About} /> // ✅ right syntax <Route path="/about" element={<About />} />

In react router v6, instead of passing a children prop to the Route components, we use the element prop, e.g. <Route path="/about" element={<About />} />.

When using react router, make sure to pass the component that should be rendered for the specific route as <Component /> and not Component.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.