DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice = Question 4

Today's Question
For this challenge, you will be editing a small React application that implements a toggle.

Solution

The boilerplate provided for this question:

import React, { useState } from 'react';
import { createRoot } from 'react-dom/client';

function Toggle() {
  function handleClick() {
    // todo
  }

  return (
    <button>ON</button>
  );
}

const container = document.getElementById('root');
const root = createRoot(container);
root.render(<Toggle />);
Enter fullscreen mode Exit fullscreen mode

The first step to solving this will be to create the toggle state required to alternate between on and off.

const [toggle, setToggle] = useState(false)
Enter fullscreen mode Exit fullscreen mode

The toggle variable will be the current state of the button, and the setToggle variable will be used to set it to the new state we want it to be. The default state is false, because we will be alternating between 2 states - On and Off. The next step would be to write the alternating logic in the function provided

function handleClick() {
setToggle(!toggle)
}
Enter fullscreen mode Exit fullscreen mode

To set the new state to what it should be, the current state simply just has to be inverted. The "!" sign is used to mean the opposite of the variable's current state. Finally, the function is assigned to the button tag, and the state is set to the variable we created.

<button onClick={handleClick}>{toggle ? "ON":"OFF"} </button>
Enter fullscreen mode Exit fullscreen mode

The onClick attribute is React's built-in attribute used to handle the event of the button being clicked. The text displayed on the button when it is clicked is being alternated by the ternary operator(?). When the state is true, the text displays "ON" and vice versa.

The final Code

import React, { useState } from 'react';
import { createRoot } from 'react-dom/client';

function Toggle() {
  const [toggle, setToggle] = useState(false)
  function handleClick() {
    // todo
    setToggle(!toggle)
  }

  return (
    <button onClick={handleClick}>{toggle ? "ON": "OFF"}</button>
  );
}

const container = document.getElementById('root');
const root = createRoot(container);
root.render(<Toggle />);
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)