Search code examples
javascriptreactjsreact-component

Get body content from custom react component


(Sorry if it's a noob question, I just started using React for a week, and didn't find the answer to this question in internet).

I have React component with two properties which is rendering one of this property into text body of <p>

function Item({ value, text }) {
  return (
    <div>
      {/* not relevant code here */}
      <p>{text}</p>
    <div>
  );
}

And I'm using it with this code:

<Item text="Foo" value="foo"/>
<Item text="Bar" value="bar"/>
<Item text="Baz" value="baz"/>

But I want to use it like this:

<Item value="foo">Foo</Item>
<Item value="bar">Bar</Item>
<Item value="baz">Baz</Item>

So how can I access the body of React Item element and how to pass it to properties?


Solution

  • You can destructure the component children from props.

    function Item({ value, children }) {
      return <div><p>{children}: {value}</p></div>;
    }
    
    function Example() {
      return (
        <div>
          <Item value="foo">Foo</Item>
          <Item value="bar">Bar</Item>
          <Item value="baz">Baz</Item>
        </div>
      );
    };
    
    ReactDOM.render(
      <Example />,
      document.getElementById("react")
    );
    p { color: red; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
    <div id="react"></div>

    Additional documentation