Reputation: 143
I have a HTML page, and I am inserting inside as a component a Reactjs. I am reading the DOM with JavaScript vanilla and I want to insert it on this new react script.
<HTML>
<div id="element">the value I want</div>
<div id="root"></div>
</HTML>
The div id "root" is where the react was inserted I want to play with the "value" from the DOM, but inside of React
Can I do it? How
Upvotes: 1
Views: 4147
Reputation: 1036
All you need is this
<div ref={(ref) => { this.myDiv = ref; }} />
And then you can get what ever you want from it with.
this.myDiv
Upvotes: 0
Reputation: 63570
Looks like you can add it to componentWillMount
before the initial render.
HTML
<div id="element">the value I want</div>
<div id="root"></div>
JSX
class Test extends React.Component {
componentWillMount() {
const { element } = this.props;
this.text = document.getElementById(element).textContent;
}
render() {
return <div>{this.text}</div>;
}
}
ReactDOM.render(
<Test element="element" />,
document.getElementById('root')
);
Upvotes: 3
Reputation: 5740
If you pass it as a prop, your component won't rely on the structure of the DOM, making it a little bit more reusable and testable:
const value = document.getElementById('element').value;
ReactDOM.render(
<App value={value}>,
document.getElementById('root')
);
or as Juan Mendes mentioned, pass in the elementId as a prop.
Upvotes: 2