Last updated: Apr 6, 2024
Reading time·2 min
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:
<Route path="/about" element={About} />
instead of <Route path="/about" element={<About />} />
.Here is a simple example of how the error occurs.
/** * ⛔️ 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.
To solve the error in this scenario, we can call the function.
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
.
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 error is when we pass an element to a React Router
route like <Route path="/about" element={About} />
.
// ⛔️ 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
.