7
7
75db772019-07-31 22:18:33
JavaScript
75db77, 2019-07-31 22:18:33

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>

CSS:
.mystyle {
  width: 100%;
  padding: 25px;
  background-color: coral;
  color: white;
  font-size: 25px;
  box-sizing: border-box;
}

JS:
function myFunction() {
   var element = document.getElementById("myDIV");
   element.classList.toggle("mystyle");
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
i1yas, 2019-07-31
@75db77

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>
  );
};

Link to sandbox

V
Vladimir, 2019-07-31
@Casufi

https://ru.reactjs.org/docs/faq-styling.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question