10 React Challenges (Beginner): Show an Alert Based on an Input

Publikováno: 10.5.2019

Events make the core of interactivity in JavaScript, from listening to form inputs, scroll events to button clicks. The knowledge of handling events in JavaScript is essential.

CodeP...

Celý článek

Events make the core of interactivity in JavaScript, from listening to form inputs, scroll events to button clicks. The knowledge of handling events in JavaScript is essential.

CodePen Final: https://codesandbox.io/s/n15z4oq24lCodePen Starter: https://codesandbox.io/s/5wz2onjn4

In this React challenge, we will carry out a DOM action after an event is fired. This event is native to the input element in React, and we'll be listening with the onChange form input event.

Events are super crucial to React and JavaScript in general.

The Challenge: Show Alert when Typing

In this challenge, you'll create a form which receives input data and alerts the window when a specific word is typed in.

The main tasks of this challenge are:

  • Store form data in state.
  • Display alert if a particular word is entered into the form.

Starter Code

Fork this starter CodeSandbox to get started: https://codesandbox.io/s/5wz2onjn4

Embed: https://codesandbox.io/s/5wz2onjn4

There are provided styles for the Sandbox in styles.css.

Here's what the final page looks like:

Hint

Look up controlled components in React, how they behave and how data is passed around and through them.

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

Solution: Show Alert when Typing

Todo: Video here.

Controlled components in React have their value determined by a state variable. Also, these components are used to set the value of an assigned state variable.

The <input> element is one such element, and it receives its value from data saved in state, and it is used to change the value of this same data in state, thereby making the state variable the single source of truth.

This challenge is solved in 3 steps:

  1. Store the input data in state.
  2. Handle input to the form.
  3. Show an alert on a specific input.

Store form data in State.

The data from the input element needs to be stored somewhere so it is used in the component. This data is saved in state. Import the useState react hook into the component with:

import React, { useState } from 'react';

Create a new state variable phrase in the component with an empty string as default.

import // ...

function App(){
    const [phrase, setPhrase] = useState('');

    return (
    // Return JSX
    )
}

Handle Input to the form

While we have the input data in state, we can set the value of the <input> element to phrase and update phrase when the data changes using the setPhrase method.

Set the value and onChange handle with:

import // ...

function App() {
  const [phrase, setPhrase] = useState('');

  return (
    <div className="App">
      <h2>What's the secret phrase?</h2>

      <input
        type="text"
        value={phrase}
        onChange={e => setPhrase(e.target.value)}
        placeholder="Super duper secret"
      />

      <p>
        Hint: It's <strong>open sesame</strong>
      </p>
    </div>
  );
}

With this, updating the form input updates the value of phrase.

How do we check the value of phrase and throw an alert when specific characters are entered?

Show an alert on specific input

This is accomplished using a simple IF statement which evaluates the value of phrase and throws an alert when a specific match is achieved.

In the App() component, create an If statement which matches the value of phrase to open sesame and throws an alert when it evaluates to true.

import // ...

function App() {
  const [phrase, setPhrase] = useState('');

  if (phrase === 'open sesame') {
    alert('You may pass!');
  }

  return (
    <div className="App">
      // return JSX
    </div>
  );
}

With this, when a user enters open sesame, the browser throws an alert with You may pass!.

Here's what the final page looks like.

You can find the completed version here: https://codesandbox.io/s/n15z4oq24l

Conclusion

In this challenge, we were able to handle data input and respond to a specific input.

Have you got questions, suggestions, and comments? We'd love to see them in the comment section. You can find other challenges here and join the live streams here. Happy keyboard slapping!

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace