TransWikia.com

How to create DOM component with start and end tag in React?

Stack Overflow Asked by doliphin on February 9, 2021

Here, I create a component SomeComponent

const SomeComponent = () => (
    <div className={"some-class"}>
        some text here
    </div>
)

I can use this component like this:

<SomeComponent text={"here is some text"} />

I would like to do the same thing, but with an opening and closing tag, as below:

<SomeComponent>
    here is some text
</SomeComponent>

How can I acheive this?

Many thanks – Oli

3 Answers

All you need to do is look for the children props.

const SomeComponent = ({ children }) => (
    <div className="some-class">
        { children }
    </div>
);

Where children can be text, HTML or other React components.

Answered by crs1138 on February 9, 2021

You can use children prop like this:

const SomeComponent = ({ children }) => (
    <div className="some-class">
        {children}
    </div>
)

And you can use it like this:

<SomeComponent>whatever content here</SomeComponent>

children prop takes not just strings, and these also work:

<SomeComponent>
  <div>hey</div>
</SomeComponent>

<SomeComponent>
  {arrayOfComponents}
</SomeComponent>

Answered by technophyle on February 9, 2021

You can access "contents" as children property.

const SomeComponent = ({ children }) => (
    <div className={"some-class"}>
      {children}
    </div>
)

Answered by Yury Tarabanko on February 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP