Functions are not valid as a React child error [Solved]

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
2 min

banner

# 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

# Returning a function instead of JSX

Here is a simple example of how the error occurs.

App.js
/** * ⛔️ Functions are not valid as a React child. */ const App = () => { const getButton = () => { return <button>Click</button>; }; // 👇️ Returning a function and not JSX element from render return <div>{getButton}</div>; }; export default App;

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

# Call the function to solve the error

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;

call the function to solve the error

The code for this article is available on GitHub

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

# Render the component to solve 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;

render the component to solve the error

The code for this article is available on GitHub

# Solve the error when using React Router

Another common cause of the 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.