skip to Main Content

I have this Layout component in React with typescript template:

import React from "react";

const Layout = (body: React.ReactNode) => {
return (
    <div>
        {/* Here will be Header */}
        {body}
    </div>
);
}

export default Layout;

and component Home:

import './style.css'
import Layout from '../../components/Layout';

const Home = () => {
return (
    <Layout>
        <section>
            {/* Some data */}
        </section>
    </Layout>
)
}

export default Home;

Typescript swears at the wrong type, so I can’t choose the type of body.
I’m just starting to learn typescript(

4

Answers


    1. body should be children
    2. Props are passed in an object so you have to wrap arguments with {}
    import React from "react";
    
    const Layout = ({ children: React.ReactNode }) => {
        return (
            <div>
                {/* Here will be Header */}
                {children}
            </div>
        );
    }
    
    export default Layout;
    
    Login or Signup to reply.
  1. The first parameter of a React function component is an object of properties typically called "props".

    The children prop is what is what JSX child nodes are passed as therefore you can access them via your prop object as such:

    const Layout = ({ children: body }: { children: React.ReactNode }) => {
      return (
        <div>
            {/* Here will be Header */}
            {body}
        </div>
      );
    }
    
    export default Layout;
    
    Login or Signup to reply.
  2. Use children instead:

    import React from "react";
    
    const Layout = ({ children }: { children: React.ReactNode }) => {
      return (
        <div>
          {children}
        </div>
      );
    }
    
    export default Layout;
    
    Login or Signup to reply.
  3. const Layout = ({ children }: { children: React.ReactNode }) => {
      return (
        <div>
          {children}
        </div>
      );
    }
    export default Layout;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search