I want Reactjs to add a class named "hello" to my div in html.
I know I can simply do this in JavaScript by writing
element.classList.add("hello");
But React shows error for the keyword ".add"
how can I do this?
I want Reactjs to add a class named "hello" to my div in html.
I know I can simply do this in JavaScript by writing
element.classList.add("hello");
But React shows error for the keyword ".add"
how can I do this?
You do this by including that class when rendering your component. So for instance, if you're doing a functional component and it returns like this:
return (
<div>
This is the content of the div
</div>
);
you'd change it to:
return (
<div className={someCondition ? "hello" : ""}>
This is the content of the div
</div>
);
...where someCondition
controls whether the div
should have the hello
class or not.
Here's an example that adds the class when you click the div
, removes it if you click again, etc.:
const {useState, Component} = React;
function FunctionalExample() {
const [hasClass, setHasClass] = useState(false);
const onClick = e => setHasClass(v => !v);
return (
<div
className={hasClass ? "hello" : ""}
onClick={onClick}
>
Example in a functional component
</div>
);
}
class ClassExample extends Component {
constructor(props) {
super(props);
this.state = {
hasClass: false
};
this.onClick = this.onClick.bind(this);
}
onClick() {
this.setState(({hasClass}) => ({hasClass: !hasClass}));
}
render() {
const {hasClass} = this.state;
return (
<div
className={hasClass ? "hello" : ""}
onClick={this.onClick}
>
Example in a class component
</div>
);
}
}
ReactDOM.render(
<div>
<FunctionalExample />
<ClassExample />
</div>,
document.getElementById("root")
);
.hello {
color: blue;
font-style: italic;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>