document.getElementsByClassName returns you the array of selected elements. Hence,
Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
In this case, you need to specify the index of the element to be used.
Notice, [0] below;
document.getElementsByClassName("hello")[0].style.color = 'red';
class Hello extends React.Component{
constructor(props){
super(props);
this.state = {
}
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
document.getElementsByClassName("hello")[0].style.color = 'red';
}
render(){
return (
<div className="hello" onClick={this.handleClick}> hello </div>
);
}
}
ReactDOM.render(
<Hello/>,
document.getElementById('root')
);
<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>
<div id="root"></div>
To work on all the elements with the same class, you need to iterate over the array and change the colors for each.
class Hello extends React.Component{
constructor(props){
super(props);
this.state = {
}
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
let elms = document.getElementsByClassName("hello");
for(var i = 0; i < elms.length; i++) {
elms[i].style.color = 'red';
}
}
render(){
return (
<div>
<div className="hello" onClick={this.handleClick}> hello 1 </div>
<div className="hello" onClick={this.handleClick}> hello 2 </div>
<div className="hello" onClick={this.handleClick}> hello 3 </div>
</div>
);
}
}
ReactDOM.render(
<Hello/>,
document.getElementById('root')
);
<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>
<div id="root"></div>
styleprop.