React Js Get Text from div:To retrieve the text from a <div>
element in React.js, you can use the textContent
property. First, assign a ref
to the <div>
element using the useRef
hook. Then, access the current
property of the ref
to get the DOM node of the <div>
. Finally, use the textContent
property to retrieve the text within the <div>
.
How can I retrieve the text content from a `<div>` element using React.js?
This code snippet demonstrates how to use React.js to get the text content from a <div>
element. The useRef
hook is utilized to create a reference to the <div>
element. When the “Get Text” button is clicked, the handleClick
function is triggered. It retrieves the text content from the referenced <div>
using divRef.current.textContent
and displays it using an alert. This functionality allows you to obtain and display the text content of a specific <div>
element in a React.js application.
React Js Get Text from div Example
<script type="text/babel">
const { useRef } = React;
function App() {
const divRef = useRef(null);
const handleClick = () => {
const text = divRef.current.textContent;
alert(text);
};
return (
<div className='container'>
<h3>React Js Get Text from div</h3>
<div ref={divRef}>
This is some text inside the div</div>
<button onClick={handleClick}>Get Text</button>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('app'));
</script>
Output of React Js Get Text from div
