Get a JSX's elements class name after load and on change

Viewed 266

I'm a bit lost learning React here.

I'm trying to get the class name of an element so I can inject an inline color depending on that class name. For example, if the element below has the class 'Active'.

<li className="active" >

I was experimenting trying to use the onChange event to see if it worked but I can't seem to fetch and print anything in the console. I assumed the event would have triggered after load and when the clase name changes, doesn't seem the case.

<li className="active" onChange={(e)=> {(console.log(e.target.className))}}

I've read a bit about React refs but it seems too much for such a simple thing. What am I missing here?

1 Answers

You don't need to use onChange event. You probably want to use the document object wherever you want to change the style of an element.

        document.getElementsByClassName("Active")[0].style.color = '#fff';

You can use it in a function and trigger it wherever you want, or just simply put it inside useEffect hook to execute on component mount.

Related