Categories
React Projects

Create a Video Player with React and JavaScript

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 video player 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 video-player

with NPM to create our React project.

Create the Video Player

To create the video player, we write:

import React, { useRef, useState } from "react";

export default function App() {
  const videoPlayer = useRef();
  const [currentTime, setCurrentTime] = useState(0);
  const [seekValue, setSeekValue] = useState(0);

  const play = () => {
    videoPlayer.current.play();
  };

  const pause = () => {
    videoPlayer.current.pause();
  };

  const stop = () => {
    videoPlayer.current.pause();
    videoPlayer.current.currentTime = 0;
  };

  const setSpeed = (speed) => {
    videoPlayer.current.playbackRate = speed;
  };

  const onPlaying = () => {
    setCurrentTime(videoPlayer.current.currentTime);
    setSeekValue(
      (videoPlayer.current.currentTime / videoPlayer.current.duration) * 100
    );
  };

  return (
    <div className="App">
      <video
        width="320"
        height="240"
        ref={videoPlayer}
        onTimeUpdate={onPlaying}
      >
        <source
          src="https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4"
          type="video/mp4"
        />
        Your browser does not support the video tag.
      </video>
      <br />
      <p>{currentTime}</p>
      <input
        type="range"
        min="0"
        max="100"
        step="1"
        value={seekValue}
        onChange={(e) => {
          const seekto = videoPlayer.current.duration * (+e.target.value / 100);
          videoPlayer.current.currentTime = seekto;
          setSeekValue(e.target.value);
        }}
      />
      <div>
        <button onClick={play}>play</button>
        <button onClick={pause}>pause</button>
        <button onClick={stop}>stop</button>
        <button onClick={() => setSpeed(0.5)}>0.5x</button>
        <button onClick={() => setSpeed(1)}>1x</button>
        <button onClick={() => setSpeed(1.5)}>1.5x</button>
        <button onClick={() => setSpeed(2)}>2x</button>
      </div>
    </div>
  );
}

We create a videoPlayer ref that we assign to the video element.

Then we define the currentTime state to get the current play time.

seekValue has the position to seek to.

Next, we define the play function that gets the video player element’s ref and call play on it.

Likewise, we call pause in pause .

And in stop , we call pause and set the currentTime of the video element to 0.

In setSpeed , we call setCurrenTime to set the current play time of the video.

And we call setSeekValue to move the video seek slider input.

Below that, we add the video element.

We set the size and assign a ref to it so we can use it in the functions.

We also set the onTimeUpdate handler to the onPlaying function to get the set the current play time and seek value.

The source element has the video source.

Below that, we show the currentTime value in seconds.

And below that, we show the range input to let us set the progress of the video.

The value prop is set to seekValue to move the slider dot as the video plays.

And in the onChange function, we set the currentTime and call setSeekValue to set the seekValue state.

Below that, we have the play, pause, and stop buttons that calls the functions above when we click them.

And the other buttons call setSpeed when we click them.

Conclusion

We can create a video player easily with React and JavaScript.

Categories
React Projects

Create an Accordion Component with React and JavaScript

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 an accordion component 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 accordion

with NPM to create our React project.

Create the Accordion

To create the accordion, we write:

import React, { useState } from "react";

export default function App() {
  const [contents, setContents] = useState(
    Array(10)
      .fill()
      .map((_, i) => {
        return {
          title: `title ${i}`,
          description: `description ${i}`,
          expanded: false
        };
      })
  );

  return (
    <div className="App">
      <style>
        {`
          .title {
            cursor: pointer;
            display: flex;
            justify-content: space-between;
          }

          .title,
          .description {
            border: 1px solid black;
            padding: 5px;
          }
        `}
      </style>
      {contents.map((c, i) => {
        return (
          <div key={c.title}>
            <div
              className="title"
              onClick={() => {
                const c = [...contents];
                c[i].expanded = !c[i].expanded;
                setContents(c);
              }}
            >
              <div>
                <b>{c.title}</b>
              </div>
              <div>
                {c.expanded ? <span>&#x2191;</span> : <span>&#x2193;</span>}
              </div>
            </div>
            {c.expanded && <div className="description">{c.description}</div>}
          </div>
        );
      })}
    </div>
  );
}

We have the contents array with the accordion contents.

Next, we add the style tag to add the styles for the accordion title and content.

Then we render the contents array into an accordion with the title div.

The onClick prop is set to a function that copies the contents array.

Then we toggle the expanded property of the contents entry with index i .

Then we call setContents with c to update the contents array.

Inside the wrapper, we show the c.title value.

And below that, we add the code for showing the arrows to the right of c.title according to the value of c.expanded .

&#x2191; is the up arrow, and &#x2193; is the down arrow.

And below that, we show the description div when c.expanded is true .

Conclusion

We can add an accordion with Reactr and JavaScript.

Categories
React Projects

Create a Tooltip with React and JavaScript

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 tooltip 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 tooltip

with NPM to create our React project.

Create the Tooltip

To create the tooltip, we write:

import React, { useState } from "react";

export default function App() {
  const [show, setShow] = useState(false);
  const [clientX, setClientX] = useState(0);
  const [clientY, setClientY] = useState(0);

  const onHover = (e) => {
    const { clientX, clientY } = e;
    setShow(true);
    setClientX(clientX);
    setClientY(clientY);
  };

  return (
    <div className="App">
      <style>
        {`
          #container {
            width: 95vw;
            height: 95vh;
            align-items: center;
            display: flex;
            justify-content: center;
          }

          #tooltip {
            border: 1px solid black;
            padding: 5px;
            position: absolute;
            background-color: white;
          }
          `}
      </style>
      <button onMouseOver={onHover}>hover me</button>
      {show && (
        <div
          id="tooltip"
          style={{ top: `${clientY}px`, left: `${clientX}px` }}
          onMouseOut={() => setShow(false)}
        >
          tooltip
        </div>
      )}
    </div>
  );
}

We have the show , clientX and clientY states that lets us set whether to show the tooltip, and its position respectively.

Next, we define the onHover function.

It gets the clientX and clientY values from the mouse event object.

Then call setShow to show the tooltip.

And setClientX and setClientY sets the position of the tooltip.

Next, we add the styles for the tooltip.

We make its position absolute so that it can show on top of other items.

The hover me button runs onHover when we hover over it.

And then we display the tooltip div if show is true .

We set the style prop to an object with the top and left positions to set the tooltip position.

onMouseOut is set to a function that calls setShow with false to hide the tooltip.

Conclusion

We can create a tooltip easily with React and JavaScript.

Categories
React Projects

Create a Hi-Low Card Game with React and JavaScript

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 hi-low card game 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 hi-low-card-game

with NPM to create our React project.

Create the Hi-Low Card Game

To create the hi-low card game, we write:

import React, { useEffect, useState } from "react";

const suits = ["diamonds", "clubs", "hearts", "spades"];
const values = ["ace", 2, 3, 4, 5, 6, 7, 8, 9, 10];
const initCards = [];
for (const s of suits) {
  for (const v of values) {
    initCards.push(`${s}_${v}`);
  }
}

export default function App() {
  const [score, setScore] = useState(0);
  const [cards, setCards] = useState(
    [...initCards].sort(() => Math.random() - 0.5)
  );
  const [drawnCards, setDrawnCards] = useState([]);
  const [guess, setGuess] = useState("lower");

  const draw = (e) => {
    e.preventDefault();
    setCards((cards) => cards.slice(0, cards.length - 1));
    setDrawnCards((drawnCards) => [...drawnCards, cards[cards.length - 1]]);
  };

  useEffect(() => {
    const indexLastCard = initCards.indexOf(drawnCards[drawnCards.length - 2]);
    const indexDrawnCard = initCards.indexOf(drawnCards[drawnCards.length - 1]);

    if (
      (indexLastCard < indexDrawnCard && guess === "higher") ||
      (indexLastCard > indexDrawnCard && guess === "lower")
    ) {
      setScore((score) => score + 1);
    }
  }, [drawnCards, guess, cards]);

  return (
    <div className="App">
      <form onSubmit={draw}>
        <select value={guess} onChange={(e) => setGuess(e.target.value)}>
          <option>lower</option>
          <option>higher</option>
        </select>
        <button type="submit">guess</button>
      </form>
      <p>score: {score}</p>
      <p>last drawn card</p>
      {drawnCards[drawnCards.length - 2] && (
        <img
          alt="last drawn card"
          src={`https://tekeye.uk/playing_cards/images/svg_playing_cards/fronts/${
            drawnCards[drawnCards.length - 2]
          }.svg`}
        />
      )}

      <p>currently drawrn card</p>
      {drawnCards[drawnCards.length - 1] && (
        <img
          alt="currently drawn card"
          src={`https://tekeye.uk/playing_cards/images/svg_playing_cards/fronts/${
            drawnCards[drawnCards.length - 1]
          }.svg`}
        />
      )}
    </div>
  );
}

We have the suits and values arrays which are used to create the initCards array with all the card values.

Then we define the score , cards , drawnCartds , and guess states.

score has the player’s score.

cards have the cards that haven’t been drawn yet.

drawnCards have the drawn cards.

guess has the guess value.

Next, we defined the draw function.

Inside it, we call e.preventDefault() to let us do client-side submission.

Then we call setCards to draw the cards by call slice to get rid of the last entry from cards .

Also, we update the drawnCards state by passing in a callback that returns an array with the existing drawnCards entry and the last card from cards .

Next, we have the useEffect hook that gets the index of the last drawn card stored in indexLastCard .

And we also have the index of the currently drawn card stored in indexDrawnCard .

Then we see if the guess value matches the comparison of the magnitude of the last drawn card and the currently drawn card.

We can compare by their indexes since initCards have the cards in order from smallest to largest.

If the condition is true , then we call setScore to increment the score by 1.

Next, we define the form with the select dropdown to let us choose lower or higher.

We get the selected value with value and set the value with the onChange callback.

onSubmit is set to submit so we run it when we click on guess.

Below that, we display the score .

Then we display the last drawn card and currently drawn card by getting the index of drawnCards .

Conclusion

We can create a hi-low card game with React and JavaScript.

Categories
React Projects

Create a Click Shape Game with React and JavaScript

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 click shape game 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 click-shape-game

with NPM to create our React project.

Create the Click Shape Game

To create the click shape game, we write:

import React, { useState } from "react";

export default function App() {
  const [score, setScore] = useState(0);
  const [circleX, setCircleX] = useState();
  const [circleY, setCircleY] = useState();
  const [timer, setTimer] = useState();

  const onClick = () => {
    setScore((s) => s + 1);
  };

  const start = () => {
    const timer = setInterval(() => {
      setCircleX(Math.floor(Math.random() * window.innerWidth));
      setCircleY(Math.floor(Math.random() * (window.innerHeight - 50) + 50));
    }, 2000);
    setTimer(timer);
  };

  const end = () => {
    clearInterval(timer);
    setScore(0);
    setCircleX(undefined);
    setCircleY(undefined);
  };

  return (
    <div className="App">
      <style>
        {`
        .circle {
          border: 1px solid black;
          width: 50px;
          height: 50px;
          border-radius: 50%;
        }
        `}
      </style>
      <button onClick={start}>start game</button>
      <button onClick={end}>end game</button>
      <p>score: {score}</p>
      {circleX && circleY && (
        <div
          className="circle"
          style={{
            position: "absolute",
            top: `${circleY}px`,
            left: `${circleX}px`
          }}
          onClick={onClick}
        >
          &nbsp;
        </div>
      )}
    </div>
  );
}

We have the score , circleX , circleY and timer states.

score has the player’s score.

circleX and circleY has the x and y coordinates of the top left corner of the circle.

timer has the timer that’s run to let us set circleX and circleY to random numbers to let us display the circle at random locations.

Next, we define the onClick function to increase the score.

start calls setInterval to run the timer to set circleX and circleY every 2 seconds.

We call setTimer to set timer so that we call clearInterval on it later to end the game.

The end function calls clearInterval to clear the timer and reset all the other states to the initial values.

Below that, we have the style tag to make the circle class have the border-radius properties to make a div become a circle.

The buttons let us start or end the game when we click the buttons.

Then we display the score below that.

And then we display the circles by setting the circleX and circleY as the values of top and left .

We pass the onClick function to the onClick prop to let us increase the score when we click on a circle.

Conclusion

We can create a click shape game easily with React and JavaScript.