Categories
React Projects

Create a Background Color Switcher App with Vue 3 and JavaScript

Spread the love

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a background color switcher app with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app background-color-switcher

with NPM to create our React project.

Create the Background Color Switcher App

To create the background color switcher app, we write:

import React, { useState } from "react";
const colors = ["red", "green", "blue", "yellow"];

export default function App() {
  const [backgroundColor, setBackgroundColor] = useState("");

  return (
    <div
      className="App"
      style={{
        backgroundColor
      }}
    >
      <style>
        {`
        .circle {
          border-radius: 50%;
          width: 50px;
          height: 50px;
          border: 1px solid black;
          display: inline-block;
          cursor: pointer;
        }

        #screen {
          width: 100vw;
          height: 100vh;
        }
      `}
      </style>
      {colors.map((c) => {
        return (
          <div
            key={c}
            style={{
              backgroundColor: c
            }}
            class="circle"
            onClick={() => setBackgroundColor(c)}
          ></div>
        );
      })}
    </div>
  );
}

We have the colors array with the colors we can switch to.

In App , we have the backgroundColor state which is used to set the background color of the wrapper div.

The style tag has the styles for the circles, which are divs we return in the map callback.

We can make a circle by setting border-radius to 50%.

Also, we set the border to make the circle edge appear.

We set cursor to pointer so that we see a hand when we hover over the circle.

In the colors.map callback, we return a div with the style with the backgroundColor set to the color c in the colors array.

And we have an onClick listener that calls setBackgroundColor to set the color.

Conclusion

We can add a background color switcher with React and JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *