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?
When the button element is clicked, the click event gets triggered, the value of the tagName property can be used to find out HTML element the source of the event and innerText property can be used to find out text written in that HTML element.
getElementById() method in React is using refs. To select an element, set the ref prop on it to the return value of calling the useRef() hook and access the dom element using the current property on the ref , e.g. ref. current .
This method is used to access any DOM element in a component and it returns a mutable ref object which will be persisted as long as the component is placed in the DOM. If we pass a ref object to any DOM element, then the. current property to the corresponding DOM node elements will be added whenever the node changes.
createRef can be used in both class and functional components.
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>
Add a ref to To MyElem:
<MyElem ref="elem">My text here<MyElem>
Then you can refer to your element elsewhere with:
this.refs.elem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With