Dmitry Samoylenko
Dmitry Samoylenko

Reputation: 13

How to create React component with components inside it?

I need something like this:

<Component>
    <Component.Child1>Test 1</Component.Child1>
    <Component.Child2>Test 2</Component.Child2>
</Component>

I noticed that some React UI frameworks have an implementation of this feature, e.g. Ant Design (<Layout />), Semantic UI (<Button />), and Blueprint (<Tabs2 />).
I have tried to find how to do the same component but found an article about dot notation. With it, I can use child components, but can't use a parent as a component.
So, what is the appropriate way to create components that can be used in JSX with child components as well?

Clarification. What I have:

const Component = (props) => (<div className="someClass">{props.children}</div>)
const Child = () => (<div>Child content</div>)

What I want:

const App = () => (
    <Component>
        <Component.Child>Test 1</Component.Child>
    </Component>
)

Upvotes: 1

Views: 678

Answers (1)

caesay
caesay

Reputation: 17271

const Component = (props) => (<div className="someClass">{props.children}</div>)
const Child = () => (<div>Child content</div>)

Well you're so close! you just need to assign the child to the parent as a property.

Component.Child = Child;

Now you can use <Component /> and <Component.Child /> as you desire.

Upvotes: 2

Related Questions