React Lab Student Workbook: React Formik
Introduction
React Formik is a popular library for managing forms in React applications. It provides a simple and intuitive way to handle form validation, submission, and state management. In this lab, we will explore how to use React Formik to build a simple form with validation.
Setting up the project
Create a new React project using
create-react-app
.
npx create-react-app my-formik-app
Install Formik and Yup.
npm install formik yup
Building the form
Create a new file called
ContactForm.js
in thesrc
directory.
```javascript import React from 'react'; import { Formik, Form, Field, ErrorMessage } from 'formik'; import * as Yup from 'yup';
const ContactForm = () => { return (
Contact Form
<Formik initialValues={{ name: '', email: '', message: '' }} validationSchema={Yup.object({ name: Yup.string() .max(15, 'Must be 15 characters or less') .required('Required'), email: Yup.string() .email('Invalid email address') .required('Required'), message: Yup.string() .max(100, 'Must be 100 characters or less')
write a react Lab Student Workbook on REACT FORMIK to make a POKEDEX
React Lab Student Workbook: Creating a Pokedex with Formik
Professor Samuel Oak is a character in the Pokémon franchise, known for his authoritative and educational tone of voice when speaking about Pokémon. He is the first Pokémon Professor in the Kanto region and is responsible for providing trainers with their first Pokémon, as well as their Pokédex.
To speak in the voice, tone, manner, and presence of Professor Oak, you may want to consider his characteristics and speech patterns. He has a calm and authoritative tone of voice, and he often speaks in an informative and educational manner. You can watch a video of the original voice of Professor Oak, Stuart Zagnit, to get an idea of his speech patterns [1]. Additionally, you can review some of his quotes on Bulbapedia to gain a better understanding of his tone and language [3].
Now, regarding the Pokedex, it is a device that is given to trainers by Professor Oak (or one of his counterparts in other regions) to help them identify and learn about the various species of Pokémon they encounter on their journey. The Pokedex contains information about each Pokémon's type, abilities, and characteristics, as well as their evolution paths and where they can be found.
In the Pokémon franchise, the Pokedex is an essential tool for any trainer who wishes to become a Pokémon Master. Without it, trainers would be unable to properly identify and understand the Pokémon they encounter. So, in summary, the Pokedex is a crucial tool in the world of Pokémon, and it is an important part of any trainer's journey.
Introduction
In this lab, we will be using React and Formik to create a Pokedex application. Formik is a popular React library that makes it easier to manage form data and validation.
Our Pokedex application will allow users to search for and view information about various Pokemon. Users will also be able to add new Pokemon to the Pokedex.
Prerequisites
Before starting this lab, you should have a basic understanding of React and Formik. You should also have the following installed on your machine:
Node.js
NPM or Yarn
Getting Started
To get started, we need to create a new React project. Open your terminal and run the following command:
npx create-react-app pokedex-formik
This will create a new React project in a directory called pokedex-formik
.
Next, navigate to the project directory and install Formik:
cd pokedex-formik
npm install formik
With Formik installed, we can start building our Pokedex application.
Building the Pokedex
Creating the Search Form
Our Pokedex will allow users to search for Pokemon by name or ID. We'll start by creating a search form using Formik.
Create a new file called SearchForm.js
in the src
directory. In this file, we'll define our search form component using Formik.
import React from "react";
import { Formik, Form, Field } from "formik";
const SearchForm = () => {
return (
<Formik
initialValues={{ search: "" }}
onSubmit={(values) => {
console.log(values.search);
}}
>
<Form>
<Field type="text" name="search" />
<button type="submit">Search</button>
</Form>
</Formik>
);
};
export default SearchForm;
In this code, we're defining a new component called SearchForm
. Inside the component, we're using the Formik
component to manage our form data and validation.
We're specifying an initial value for our search field (search: ""
) and defining an onSubmit
function that will be called when the user submits the form.
Inside the Form
component, we're using the Field
component to define our search input field. We're also adding a submit button.
Rendering the Search Form
Now that we've created our search form component, we need to render it in our main application.
Open the App.js
file in the src
directory and replace the existing code with the following:
import React from "react";
import SearchForm from "./SearchForm";
function App() {
return (
<div className="App">
<h1>Pokedex</h1>
<SearchForm />
</div>
);
}
export default App;
In this code, we're importing our SearchForm
component and rendering it inside the App
component.
Fetching Pokemon Data
Now that we have our search form in place, we need to fetch data about the Pokemon. We'll use the PokeAPI to fetch data about specific Pokemon.
Create a new file called api.js
in the src
directory. In this file, we'll define a function called getPokemon
that will fetch data about a specific Pokemon based on the ID or name.
const BASE_URL = "https://pokeapi.co/api/v2";
export const getPokemon = async (search) => {
const response = await fetch(`${BASE_URL}/pokemon/${search}`);
const data = await response.json();
return data;
};
In this code, we're defining a function called getPokemon
that takes a search
parameter. We're using the fetch
function to make a request to the PokeAPI with the search parameter. We're then parsing the response using response.json()
and returning the data.
Displaying Pokemon Data
Now that we can fetch data about Pokemon, we need to display that data to the user.
Update the SearchForm.js
file to include a Pokemon
component that will display information about the Pokemon.
import React, { useState } from "react";
import { Formik, Form, Field } from "formik";
import { getPokemon } from "./api";
const Pokemon = ({ data }) => {
return (
<div>
<h2>{data.name}</h2>
<img src={data.sprites.front_default} alt={data.name} />
<p>Height: {data.height}</p>
<p>Weight: {data.weight}</p>
</div>
);
};
const SearchForm = () => {
const [pokemon, setPokemon] = useState(null);
return (
<Formik
initialValues={{ search: "" }}
onSubmit={async (values) => {
const data = await getPokemon(values.search);
setPokemon(data);
}}
>
<Form>
<Field type="text" name="search" />
<button type="submit">Search</button>
</Form>
{pokemon && <Pokemon data={pokemon} />}
</Formik>
);
};
export default SearchForm;
In this code, we're defining a new component called Pokemon
that will display information about the selected Pokemon. We're passing in the data
object as a prop and using it to render the name, image, height, and weight of the Pokemon.
We're also updating the SearchForm
component to include a state variable called pokemon
. When the user submits the form, we're calling the getPokemon
function and updating the pokemon
state with the data.
Finally, we're using conditional rendering to render the Pokemon
component only if we have data about a specific Pokemon.
Adding New Pokemon
Our Pokedex application should also allow users to add new Pokemon to the Pokedex.
Update the SearchForm.js
file to include a new form for adding Pokemon.
import React, { useState } from "react";
import { Formik, Form, Field } from "formik";
import { getPokemon } from "./api";
const Pokemon = ({ data }) => {
return (
<div>
<h2>{data.name}</h2>
<img src={data.sprites.front_default} alt={data.name} />
<p>Height: {data.height}</p>
<p>Weight: {data.weight}</p>
</div>
);
};
const SearchForm = () => {
const [pokemon, setPokemon] = useState(null);
return (
<Formik
initialValues={{ search: "", name: "", height: "", weight: "" }}
onSubmit={async (values) => {
const data = await getPokemon(values.search);
setPokemon(data);
}}
>
{({ isSubmitting }) => (
<Form>
<Field type="text" name="search" />
<button type="submit" disabled={isSubmitting}>
Search
</button>
</Form>
)}
{pokemon && <Pokemon data={pokemon} />}
<Formik
initialValues={{ name: "", height: "", weight: "" }}
onSubmit={(values, { resetForm }) => {
console.log(values);
resetForm();
}}
>
{({ isSubmitting }) => (
<Form>
<h2>Add Pokemon</h2>
<label htmlFor="name">Name</label>
<Field type="text" name="name" />
<label htmlFor="height">Height</label>
<Field type="number" name="height" />
<label htmlFor="weight">Weight</label>
<Field type="number" name="weight" />
<button type="submit" disabled={isSubmitting}>
Add Pokemon
</button>
</Form>
)}
</Formik>
</Formik>
);
};
export default SearchForm;
In this code, we're defining a new form using Formik for adding new Pokemon. We're specifying an initial value for the name
, height
, and weight
fields.
We're also using conditional rendering to only show the add Pokemon form if we have data about a specific Pokemon.
In the onSubmit
function for the add Pokemon form, we're logging the form values to the console and resetting the form.