React: Access element's text
You use the children
property, which contains the children of your element (which might be text or an array of children [I think it's always an array when it's not text], see the link for the gory details). E.g.:
const Foo = props => {
console.log(props.children);
return (
<div>{props.children}</div>
);
};
ReactDOM.render(
<Foo>Hi There</Foo>,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
That uses a stateless functional component (SFC), but it's the same for Component
subclasses:
class Foo extends React.Component {
render() {
console.log(this.props.children);
return (
<div>{this.props.children}</div>
);
}
};
ReactDOM.render(
<Foo>Hi There</Foo>,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Here's an example of the fact that children
isn't just for text:
class Foo extends React.Component {
render() {
console.log(this.props.children);
return (
<div>{this.props.children}</div>
);
}
};
ReactDOM.render(
<Foo>
<div>Hi there</div>
<Foo><span>nested Foo > Foo > span</span></Foo>
</Foo>,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>