Subscribe Us

React List | React Forms | React Router | React JS | Dark Watcher

 

React Lists

In React we render lists with loop

map()

An example of map:

function App() {
  const languages = ['JS', 'Python', 'Java', 'C', 'C++', 'C#'];

  return (
    <div className="App">
      {languages.map((language) => {
        return <div>I love {language}</div>
      })}
    </div>
  );
}

Output: 

Keys

With keys React keep record of elements. This ensures that if an item is updated or removed, only that item will be re-rendered instead of the entire list. Example:

function App() {

  const languagesDict = [
    { id: 1, language: 'JS' },
    { id: 2, language: 'Python' },
    { id: 3, language: 'Java' },
    { id: 4, language: 'C' },
    { id: 5, language: 'C++' },
    { id: 6, language: 'C#' }
  ];

  return (
    <div className="App">
      {languagesDict.map((language) => {
        return <div key={language.id}>
          {language.id}. {language.language}
        </div>
      })}
    </div>
  );
}

Output: 

An example of map:

function App() {
  const languages = ['JS', 'Python', 'Java', 'C', 'C++', 'C#'];

  return (
    <div className="App">
      {languages.map((language) => {
        return <div>I love {language}</div>
      })}
    </div>
  );
}

Output: 


React Forms

React Forms are mostly like normal HTML forms, except we use state in this to handle inputs. 

Handling Forms

In React all the data is handled by component and stored in component state. We can change state with event handlers in the onChange attribute, like this:

import { useState } from 'react';

function Form() {
  const [email, setEmail] = useState('');

  return (
    <form>
      <label>
        Enter your email: <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
      </label>
    </form>
  )
}

export default Form;

 

Submitting Form

We can submit form with onSubmit attribute for the <form>

import { useState } from 'react';

function Form() {
  const [email, setEmail] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Your email is: ${email}`)
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Enter your email: <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
      </label>
      <input type="submit" />
    </form>
  )
}

export default Form;

 

Multiple Inputs

We don't have to make multiple states for multiple inputs, we can save all values in one, like this:

import { useState } from 'react';

function Form() {
  const [data, setData] = useState({});

  const handleChange = (e)=>{
    setData({...data, [e.target.name]: e.target.value})
  }

  const handleSubmit = (e) => {
    e.preventDefault();
    alert(`Your email is: ${data.email} and your name is: ${data.name}`)
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Enter your email: <input type="email" name='email' value={data.email} onChange={handleChange} />
      </label>
      <label>
        Enter your name: <input type="text" name='name' value={data.name} onChange={handleChange} />
      </label>
      <input type="submit" />
    </form>
  )
}

export default Form;

Here in handleChange we used Spread Operators. We are basically saying keep whole data as it was, just change this name's value. Then it is saved as an object so we are getting that by data.email and data.name

React Router

React router is used for page routing as React App doesn't include it as default. 

Add React Router

To install React router, run this in your terminal:

npm i -D react-router-dom

Creating Multiple Routes

To do this first we need to create multiple files and to keep code clean, we will make a folder and make all the pages there, hence we will create a folder named pages in src

Folder Structure:

src/pages/:

  • Home.js
  • Blogs.js
  • Contact.js
  • Nopage.js

Usage

Now we will make routes in src/index.js, like this:

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter, Routes, Route } from "react-router-dom";
import reportWebVitals from './reportWebVitals';
import Home from "./pages/Home";
import Blogs from "./pages/Blogs";
import Contact from "./pages/Contact";
import NoPage from "./pages/NoPage";

export default function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route index element={<Home />} />
        <Route path="/blogs" element={<Blogs />} />
        <Route path="/contact" element={<Contact />} />
        <Route path="*" element={<NoPage />} />
      </Routes>
    </BrowserRouter>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

reportWebVitals();

Home.js

Make all the Navigation links using <Link> tag, like this:

import { Link } from "react-router-dom";

const Home = () => {
    return (
        <>
            <nav>
                <ul>
                    <li>
                        <Link to="/">Home</Link>
                    </li>
                    <li>
                        <Link to="/blogs">Blogs</Link>
                    </li>
                    <li>
                        <Link to="/contact">Contact</Link>
                    </li>
                </ul>
            </nav>
        </>
    )
};

export default Home;

Blogs.js

const Blogs = () => {
    return <h1>Blogs</h1>;
};

export default Blogs;

Contact.js

const Contact = () => {
    return <h1>Contact</h1>;
};

export default Contact;

NoPage.js

const NoPage = () => {
    return <h1>404</h1>;
};

export default NoPage;

This is made for any route that doesn't exist. To show 404 error there! 

Post a Comment

0 Comments