Home > Back-end >  Unable to pass react props.children
Unable to pass react props.children

Time:11-12

I am using react. When I pass props.children to the Header component, I get the following error.
I think the type is correct because I am passing React.
I don't know why the error occurs.

error
react-dom.development.js?61bb:13231 Uncaught Error: Objects are not valid as a React child (found: object with keys {children}). If you meant to render a collection of children, use an array instead.
import React from 'react';
import styled from 'styled-components';

export const Header: React.FC = (children) => {
  return <Head>{children}</Head>;
};

const Head = styled.div`
  background: #8b8b8b;
`;

const Home = () => {
  return (
     <div>
      <Header>
        <span>home</span>
      </Header>
     <div>
  );
};


export default Home;

CodePudding user response:

You just named your props as children, try:

export const Header: React.FC = ({children}) => {
  return <Head>{children}</Head>;
};

CodePudding user response:

Let's just take a step back from destructuring for a second because it confuses a lot of JS beginners.

By default, your component receives an argument which is a bunch of properties, so we usually call it props. We can get particular properties from this props object like so:

export const Header = (props) => {
  console.log(props)
  return <Head>{props.children}</Head>;
};

Then once you get your head around destructuring, you'll notice we can do this in a faster, cleaner manner to get properties from our props object.

export const Header = ({ children }) => {
  console.log(children)
  return <Head>{children}</Head>;
};

The trade-off is we can't do props.something now, we'll need to add something to the restructure... but our code looks cleaner.

  • Related