Answer the question
In order to leave comments, you need to log in
How to remake the class switching code in React as in the example?
How to remake the class switching code in React as in the example?
html:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="index.js"></script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is a DIV element.
</div>
</body>
</html>
.mystyle {
width: 100%;
padding: 25px;
background-color: coral;
color: white;
font-size: 25px;
box-sizing: border-box;
}
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.toggle("mystyle");
}
Answer the question
In order to leave comments, you need to log in
You need to store the state of this element, the question is where. The component can accept a prop and an onClick callback as input, or the component can manage the state internally and handle the click. For the first, you'll either need a parent component with state and handler functions, or a separate state store. The option with internal state storage is simpler (but not always suitable):
const Element = props => {
const [styleEnabled, setStyle] = useState(false);
return (
<div
className={`myDIV ${styleEnabled ? "mystyle" : ""}`}
onClick={e => setStyle(!styleEnabled)}
>
Toggle me
</div>
);
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question