2

How to change style using javascript in reactjs

class Hello extends Component{
    constructor(props){
        super(props);
        this.state = {
        }
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        document.getElementsByClassName("hello").style.color = 'red';
    }
    render(){
        return (
            <div className="hello" onClick={this.handleClick}>hello</div>
        );

    }
}

ReactDOM.render(
    <Hello/>,
    document.getElementById('root')
);

I am getting error

TypeError: Cannot set property 'color' of undefined

2
  • This can happen if: 1)No elements were found with that class. 2) If an invalid index is used to access the elements in the array. Commented Aug 2, 2018 at 5:55
  • The preferable way would be to not mutate DOM yourself, let React take care of it. React does this more efficiently for you. Use the style prop. Commented Aug 2, 2018 at 6:52

2 Answers 2

4

You can probably use react way too

class Hello extends Component{
    constructor(props){
        super(props);
        this.state = {
            customColor: {}
        }
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState(() => ({ customColor: { color: 'red' } }));
    }

    render(){
        return (
            <div className="hello" style={this.state.customColor} onClick={this.handleClick}>hello</div>
        );

    }
}

ReactDOM.render(
    <Hello/>,
    document.getElementById('root')
);

The benefit of doing so is that any component created either single or multiple times each of these will have there on set of state and functions and everything. So when I handleclick for one component then it will affect the same component giving it an isolation.

Sign up to request clarification or add additional context in comments.

Comments

3

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>

10 Comments

This is working fine but how can i do this for all element of same class
Added to the answer according to your comment
Smiles, I dont want to use for lop. I have to find another way. To change style dynamically
To be honest, that's a different question. I was just helping you to get your original problem solved. If your original question is resolved, feel free to accept the answer, so that somebody stuck with similar question can also be benefitted from this. Hope that helps.
Sure. I will. But it didnt solve my problem. But You are correct.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.