Skip to content

Latest commit

 

History

History
59 lines (41 loc) · 1.93 KB

dynamic-styles.md

File metadata and controls

59 lines (41 loc) · 1.93 KB

Exercise: Dynamic Styles

Your task is to dynamically apply a style (color: red) to the <p>Style me</p> element in the provided React app.

The style should be applied as an inline style (i.e., via the style attribute / prop) when the <button> is clicked for the first time. Once the button is clicked again, the styling should switch back to color: white, which should also be the initial style.

Make sure that the button toggles between these two styles (color: white <=> color: red).

Here's how the finished app should look like BEFORE the button was clicked:

Before button click

Here's how it should look like AFTER the button was clicked:

after button click

And here's how it should look like when the button was clicked again:

second button click

Important: Use *React.useState()* instead of just *useState()* as the latter can cause problems in this Udemy code environment.

Starter Code:

import React from "react";

// don't change the Component name "App"
export default function App() {
  return (
    <div>
      <p>Style me!</p>
      <button>Toggle style</button>
    </div>
  );
}

Solution Code:

import React from "react";

// don't change the Component name "App"
export default function App() {
  const [toggle, setToggle] = React.useState(false);

  const toggleHandler = () => {
    setToggle(!toggle);
  };

  return (
    <div>
      <p style={{ color: toggle ? "red" : "white" }}>Style me!</p>
      <button onClick={toggleHandler}>Toggle style</button>
    </div>
  );
}