Introduction and Topic Overview

Welcome back! Today, we'll be exploring advanced form validation, techniques for passing data from a child to a parent, strategies for handling events in parent components, and the concept of props.children in React. Let's dive in!

Advanced Form Validation

To begin with, we'll be tackling form validation. It can be likened to a restaurant waiter confirming your order. In React, the useState hook is beneficial for managing form values and validation rules.

import React, { useState } from "react";

function SimpleEmailForm() {
  const [email, setEmail] = useState("");
  const handleEmailChange = (e) => {
    setEmail(e.target.value);  // The email state is updated as the user types
  };
  // Validate if the entered email is in a valid format
  const validateEmail = (e) => {
    e.preventDefault();
    const pattern = // regular expression for email
    pattern.test(email) ? alert('Email is valid') : alert('Invalid email');
  };
  return (
    <form onSubmit={validateEmail}>
      <input type="text" value ={email} onChange={handleEmailChange} />
      <button type="submit">Submit</button>
    </form>
  );
}
Data Flow: Child to Parent Components

Data in React typically flows from the top (parent) to the bottom (child). However, data can also flow in the upward direction using callback functions.

import React, { useState } from "react";

function Grandparent() {
  const [grandChildData, setGrandChildData] = useState("");
  const handleCallback = (grandChildData) => {
    setGrandChildData(grandChildData);  // The state is updated with data from the grandchild
  };
  return <Parent grandparentCallback={handleCallback}/>;
}

function Parent({ grandparentCallback }) {
  return <Child parentCallback={grandparentCallback}/>;
}

function Child({ parentCallback }) {
  return <button onClick={() => parentCallback("Data from Grandchild")}>Click</button>;
}

In this case, the grandchild component sends data to the grandparent component.

Handling Events in Parent Components

Components in React trigger functions known as "event handlers" in response to user actions. Let's examine an example:

function Parent() {
  const handleClick = () => console.log("Clicked in Child");
  return <Child onButtonClick={handleClick} />;
}

function Child({ onButtonClick }) {
  return <button onClick={onButtonClick}>Click</button>;
}

In this code, when the Child component's button is clicked, the handleClick function is triggered, which logs a message.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal