Tick Twitch
Tick Twitch

Reputation: 566

Creating A react component which can be nested

I am trying to create a component which can be reused in another component.Suppose i have a component like this

import React from 'react';

export default class Container extends React.Component {
    render() {
        return (
            <div className='col-md-4/6/7'>
                <div className='bg-dark'>
                    .......... Content Goes Here .............
                </div>
            </div>
        );
    }
}

Then i want to use the component like this...

    import React from 'react';

export default class Container extends React.Component {
    render() {
        return (
            <Container col md={4}>
                    .......... Content Goes Here .............
            </Container>
        );
    }
}

I cant achieve that .It can be somewhat {this.state.children} but dont know how can achieve it

Upvotes: 0

Views: 48

Answers (3)

akhtarvahid
akhtarvahid

Reputation: 9769

Access using this.props.children because it's class based component. if it's functional component access using props.children

export default class Container extends React.Component {
    render() {
        return (
            <div className='col-md-4/6/7'>
                <div className='bg-dark'>
                   {this.props.children}
                </div>
            </div>
        );
    }
}

Upvotes: 0

Simone
Simone

Reputation: 21262

Simply edit the Container to render children:

import React from 'react';

export default class Container extends React.Component {
    render() {
        return (
            <div className='col-md-4/6/7'>
                <div className='bg-dark'>
                    { this.props.children }
                </div>
            </div>
        );
    }
}

And then use it:

<Container col md={4}>
    Hello, world!
</Container>

The children prop is explained in detail here: https://reactjs.org/docs/composition-vs-inheritance.html

Upvotes: 1

Joe Lloyd
Joe Lloyd

Reputation: 22323

Props.children

const Wrapper = (props) => <div>{props.children}</div>
const Inner = (props) => <Wrapper>some text or component</Wrapper>

Upvotes: 0

Related Questions