(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?
My simple explanation of what props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component.
change your function component to
function Item(props) {
return (
<div>
{props.children}
<div>
);
}
Reference : react's props children
@Kirill I hope this will help you 😇.
function Item({ value, children }) {
return (
<div>
{/* not relevant code here */}
{children}
<div>
);
}
Then you can call your Item like this:
<Item value="foo">Foo</Item>
<Item value="bar">Bar</Item>
<Item value="baz">Baz</Item>
also you can pass other element as children to your Item Component also:
<Item value="foo">
<p>Foo</p>
</Item>
I guess this should work.
function Item({ value, children }) {
return (
<div>
{/* not relevant code here */}
<p>{children}</p>
<div>
);
}