How can I add styling to an element in React?

In normal JavaScript you can grab an element by its id and add a style to it. For example:

var element = document.getElementById("myElement");
element.style.backgroundColor = "#f5f5f5";

My question is how you can do this in react. Is it even possible to add this style? In react im using onChange in a function outside the render(). I looked at the React DOM for styling and tried but since styling is in different function it will tell me how the variable is undefined. this is my code:

ChangeImage() {
        var imgStyles = {
            backgroundColor: '#000',
            padding: 5,
        }
    }

    render() {
        return (
            <div className="class">
                <div className="img-surround">
                <img 
                    src={this.state.file} 
                    id="img" 
                     style={imgStyles}/>
                </div>

Everything is working except styles and I even tried putting in different functions

Answer

If you want to render the element with the style you can return the element like this in a react functional component:

return <div style={{backgroundColor: "#f5f5f5"}}></div>

If you want the element to only have that style in a certain condition you can use the useState hook in a react functional component:

const [myState, setMyState] = useState(false);
return <div style={myState && {backgroundColor: "f5f5f5"}}></div>

And you should change myState’s value using setMyState however you like. For example:

const [myState, setMyState] = useState(false);
return <div onClick={() => myState ? setMyState(true) : setMyState(false)} style={myState && {backgroundColor: "f5f5f5"}}></div>

In this example whenever you click on the div the style is added or removed by case

Leave a Reply

Your email address will not be published. Required fields are marked *