Thomas Anderson Thomas Anderson - 1 month ago 9
React JSX Question

React: Access element's text

My component is used inside other render() like

return (<MyElem>Some text here</MyElem>)


How can I access the "Some text here" string inside my component's class?

Answer

You use the children property. 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>