10 React Challenges for Beginners - Lesson #7

React Challenge: DOM Movement with Events

Styling elements or in some instances, components in a React project is essential. Sometimes, you need to make a change in the style of an element based on changes in the application using JavaScript.

In this challenge, we will change a CSS property when a certain event is fired or a state value in the application is changed.

This challenge requires you to move the position of a provided box upwards whenever a button is clicked.

The tasks in this challenge are:

  • Create a state variable to hold the value of the transformation points.
  • Handle an event which increments or decrements the transformation points.
  • Bind the transformation using inline CSS to the created box.

Fork this CodeSandbox to get started: https://codesandbox.io/s/k3yy75w3wo

Styling is provided in the starter CodeSandbox, feel free to use it.

Here's what the final application looks like:

Try to move the box in multiple directions with various buttons. You can also have the box tracking the mouse.

Look up the transform CSS property as well as its corresponding translateY function.

Various CSS-in-JS solution exists which enable you to write CSS in JavaScript files. In this React challenge, we will update the value of a CSS property in a component using JavaScript.

For this challenge, we are required to move a provided box upwards on the click of a button. This button when clicked updates a created state value and this value is passed to the transform CSS property of the box.

The translateY function is used to displace the box in the 2D plane. This challenge is completed in 3 steps:

  • Store offset value in state.
  • Create a function to decrement the offset value.
  • Bind the offset value to the box and the function to the trigger button.

The useState React hook is used to create a state variable alongside its corresponding update method. The initial value of offsetTop is 300. This initial value will serve as the offset from the original position of the box vertically.

Create a state variable named offsetTop in the App() component and set the initial value to 300. Do this with:

jsx
import { useState } from 'react';
import ReactDOM from 'react-dom';
import './styles.css';

function App() {
  const [offsetTop, setOffsetTop] = useState(300);

  return (
    <div className="App">
      <h1>Move the Box!</h1>

      {/* handle the click event on this button */}
      <button>πŸ‘† Move Up πŸ‘†</button>

      {/* move this box using inline styles */}
      <div
        className="box"
        style={{}}
      />

    </div>
  );
}

To move the box closer to the top, reduce the value of offsetTop. Create a function which reduces its value by 50. You can use any value you want. 50 allows the box to move a good amount. Do this in App() with:

jsx
// import  ... import dependencies 

function App() {
  const [offsetTop, setOffsetTop] = useState(300);

  function moveBoxUp() {
    setOffsetTop(offsetTop - 50);
  }

  return (
    <div className="App">

      {/* App content goes in here */}

    </div>
  );
}

The moveBoxUp function will be called whenever the "Move Up" button is clicked.

We now have the transformation data with which we can move the box upward. Add an in-line style with a transformation property and its value which uses the translateY function to displace the box from the top. Do this with:

jsx
// import  ... import dependencies

function App() {
  // Component variables

  return (
    <div className="App">
      <h1>Move the Box!</h1>

      {/* handle the click event on this button */}
      <button>πŸ‘† Move Up πŸ‘†</button>

      {/* move this box using inline styles */}
      <div
        className="box"
        style={{
          transform: `translateY(${offsetTop}px)`
        }}
      />

    </div>
  );
}

Using template literals, we included the offsetTop variable in the in the transform property. This sets the box down the page by 300px.

In the "Move Up" button, use the onClick event handler to call the moveBoxUp function anytime the button is clicked. Do this with:

jsx
// import  ... import dependencies

    function App() {
      // Component variables

      return (
        <div className="App">
          <h1>Move the Box!</h1>

          {/* handle the click event on this button */}
          <button onClick={moveB}>πŸ‘† Move Up πŸ‘†</button>

          {/* move this box using inline styles */}
          <div
            className="box"
            style={{
              transform: `translateY(${offsetTop}px)`
            }}
          />

          
        </div>
      );
    }

With this, once the button is clicked, the function decrements the value of the offset from the top by 50px.

Here's what the final page looks like:

You can find the completed CodeSandbox here.

In this challenge we made a style change to a React component using JavaScript.

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)