头图

The text starts here~

Overview

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

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

functions-are-not-valid-as-react-child.png

Here is an example to show 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 problem with the snippet above is that we are returning the getButton function from the render method, instead of returning a real JSX element.

Call functions

To fix the error in this case, we can call the function.

 const App = () => {
  const getButton = () => {
    return <button>Click</button>;
  };

  // ✅ now returning the actual button
  // added parenthesis () to call the function
  return <div>{getButton()}</div>;
};

export default App;

By calling the getButton function, we return the button element to resolve the error.

If you're trying to render a real 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;

<Component />

Another cause of this error is when we pass an element for the 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 the children property to the Route component, we use the element property. For example, <Route path="/about" element={<About />} /> .

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

Summarize

Errors can be resolved in two ways:

  1. Return a component from render instead of a function.
  2. The element attribute passed to the route is <Component /> instead of Component .

chuck
303 声望41 粉丝