LeonidasFett
LeonidasFett

Reputation: 3132

Build a layout component in React and TypeScript

I don't know how to explain this so it makes sense, so I am going to use a Razor (C#) example. In Razor, we can define layout pages and then state where we want to render the body like so:

<html>
    <body>
        @RenderBody()
    </body>
</html>

So let's say I have a React component which I use for layout:

class Layout extends React.Component<any, any> {
    constructor(props) {
        super(props);
    }

    public render() {
        return (
            <Container fluid>
                <Row className="row">
                    <Col className="col-sm">
                        <NavBar />
                        //How to achieve the same functionality as RenderBody() here?
                    </Col>
                </Row>
            </Container>
        );
    }
}

So when I create a child component, I can do this:

public render(){
    return(
        <Layout>
            <div>I am some content!</div>
        </Layout>
    );
}

Is this possible? If so, how?

Upvotes: 0

Views: 5301

Answers (1)

Idrizi.A
Idrizi.A

Reputation: 12010

Yes, you can use the children prop to print whatever is inside the <Layout>. So change your Layout component to something like this:

<Container fluid>
  <Row className="row">
    <Col className="col-sm">
      <NavBar />
                        
      {this.props.children}
    </Col>
  </Row>
</Container>

Here is an answer explaining it in more detail.

Upvotes: 3

Related Questions