Friday, November 24, 2023

React Bootstrap Login Form With Validations

In this post we'll see how to create a login form with validations using React and Bootstrap 5. The login form has two fields- email and password and a submit button.

login form react

LoginForm React and Bootstrap Example

In this example Bootstrap 5 is used.

If you want to know how to download Bootstrap and use in your React application, check this post- Installing Bootstrap in React

Login.js

import { useState } from "react";

const Login = () => {
    const [formField, setState] = useState({
        email: '',
        passwd: '',
        errors: []
    });
    const handleInputChange = (event) => {
        let errors = [];
        // clear errors if any
        if (formField.errors.length > 0) {
            setState((prevState) => (
                {...prevState, errors}
            ));
        }
        const value = event.target.value;
        const name = event.target.name;
        setState((prevState) => (
            {...prevState, [name]: value}
        ));
    }
    const submitHandler = (event) => {
        event.preventDefault();
        let errors = [];
        //email regular expression pattern
        const emailRegEx = /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/;
        let isEmailValid = emailRegEx.test(formField.email.toLowerCase())
        
        if (!isEmailValid) {
            errors.push("email");
        }
        if(formField.passwd  === ""){
            errors.push("passwd");
        }

        setState((prevState) => (
            {...prevState, errors}
        ));
        // If there is error dont submit, return to form
        if (errors.length > 0) {
            return false;
        } else{
            // write code for successful submission...
            console.log('Form Submitted')
        }
    }

    const hasError = (name) => {
        //console.log("haserror " + name);
        return formField.errors.indexOf(name) !== -1;
    }

    return (
        <div className="card col-5 mt-5 mx-auto">
            <div className="card-header bg-info text-white">
            <h2>User Login</h2>
            </div>
            <div className="card-body">
                <form onSubmit={submitHandler}>
                    <div className="mb-3">
                        <label className="form-label" htmlFor="userEmail">Email</label>
                        <input type="text" 
                            className={hasError("email") ? "form-control is-invalid" :"form-control"}  
                            placeholder="Enter Email" 
                            name="email"
                            id="userEmail" 
                            value={formField.email} 
                            onChange={handleInputChange} />
                         <div className={hasError("email") ? "invalid-feedback" : ""}>
                            { hasError("email") ? <span>Please enter valid email</span> : "" }
                         </div>
                    </div>   
                    <div className="mb-3">
                        <label className="form-label" htmlFor="userPassword">Password</label>
                        <input type="password" 
                            className={hasError("passwd") ? "form-control is-invalid" :"form-control"}   
                            placeholder="Enter Password" 
                            name="passwd"
                            id="userPassword" 
                            value={formField.passwd} 
                            onChange={handleInputChange}/>
                        <div className={hasError("passwd") ? "invalid-feedback" : ""}>
                            { hasError("passwd") ? <span>Please enter password</span> : "" }
                         </div>
                    </div>  
                    <button type="submit" className="btn btn-primary">Submit</button> 
                </form>
            </div>
        </div>
    )
    
}

export default Login;

Some important points about the login form are as given below-

  1. Uses the Bootstrap card as a container for the form elements.
  2. Single state is used here with useState() hook. State is managed as an object with three properties email, passwd and an array of errors which keeps track of all the fields that fail validations. Initial state is empty string for email and passwd, empty array ([]) for errors.
  3. In input fields onChange() event handler is mapped to a single function handleInputChange() for all the fields. Note that a single setState() changes state for all the form fields. For that to work, ensure that the name you give to input fields matches the name of the properties in state object.
  4. When calling setState() to update state, spread operator is used to spread the previous state so that you can overwrite the individual fields without losing the data for other fields.
    setState((prevState) => (
        {...prevState, [name]: value}
    ));
    	
  5. Form onSubmit() event handler is mapped to submitHandler() function. That's where field validation is done and field name is pushed to errors array if field fails validation.
  6. While rendering, errors array is checked. If field exists in that array that means field failed validation.
  7. When the field fails validation Bootstrap class "is-invalid" is added which creates red border around the field. For error message "invalid-feedback" class is used. You don't need to write any css yourself.

Clicking submit without entering any values.

login form React Bootstrap

When only email is entered.

That's all for the topic React Bootstrap Login Form With Validations. If something is missing or you have something to share about the topic please write a comment.


You may also like

Monday, November 20, 2023

Nested Route in React

In the post Dynamic Route in React we have seen how you can add dynamic segments to the routes. In that kind of parent and child route scenario you can also use nested routes to create a component hierarchy and UI also looks better as you can display both parent and child components next to each other by using <Outlet /> in the parent component to render the child route's element.

Nested route in React

Nested routes or child routes in React gives you an option to place a route relative to another route which is not root route.

If you have followed example in this post React Router - Link in react-router-dom this has already been done so that the route, that points to Navigation, acts as a parent component and the other routes as nested routes.

How to create a child route in React

You place child routes in a children array within the parent route. For example, in the given route definition root route ("/") acts as a parent route for all the routes that's why all the other routes are defined as children.

Then we have a "/users" route and a dynamic route "/users/:userId", that is also done as a nested route so that the route with dynamic segment becomes a child route. That way as path we just need to give the child path segment (":userId") as it is relative to its parent.

export const router = createBrowserRouter([
    {path: "/", element: <Navigation />, errorElement: <ErrorPage />,
     children: [
        {index: true, element: <Home /> },
        {path: "users", element: <Users />,
            children: [
                {path: ":userId", element: <UserDetails/>}
            ]
        },
        {path: "about", element: <About />}
     ]
    },        
])

Note that in this route definiton, route paths are relative paths (does not begin with "/") which means paths resolve relative to the parent route. ":userId" is a child route of "users" so it builds upen the parent route meaning it resolves to "/users/:userId".

Nested Route React example

In the example we display a page with list of user names using Users Component. For the user’s name that is clicked user details are displayed using UserDetails component. Dynamic routing is used here to pass userId as route parameter. It is the same example used in Dynamic Route post but now we’ll place path with dynamic segment as a child route so that there is a component hierarchy between Users and UserDetails and we can show UserDetails data next to Users data by placing <Outlet /> in the Users (parent) component.

Route Definition

src\components\Routes\route.js

import { createBrowserRouter } from "react-router-dom";
import About from "./About";
import ErrorPage from "./ErrorPage";
import Home from "./Home";
import Navigation from "./Navigation";
import UserDetails from "./UserDetails";
import Users from "./Users";

export const router = createBrowserRouter([
    {path: "/", element: <Navigation />, errorElement: <ErrorPage />,
     children: [
        {index: true, element: <Home /> },
        {path: "users", element: <Users />,
            children: [
                {path: ":userId", element: <UserDetails/>}
            ]
        },
        {path: "about", element: <About />}
     ]
    },        
])

Providing the routes

Provide the route definition to your application using the <RouteProvider> component.

import { RouterProvider } from 'react-router-dom';
import { router } from './components/Routes/route';

function App() {
  return <RouterProvider router={router}></RouterProvider>
}

export default App;

Components

Two components that we need for user are Users and UserDetail.

src\components\Routes\Users.js

import { Link, Outlet } from "react-router-dom"

export const DUMMY_USERS = [
    {id: 1, name: "Ram", age: 23},
    {id: 2, name: "Namita", age: 25},
    {id: 3, name: "Varun", age: 32},
    {id: 4, name: "Leo", age: 28},
    {id: 5, name: "Melissa", age: 27},
]

const Users = () => {
    return(
        <>
            <div className= "row">
                <div className="col-sm-4">
                    <h2>Users</h2>
                    <ul className="list-group">

                        {DUMMY_USERS.map(user =><li className="list-group-item" key={user.id}> 
                            <Link to={user.id.toString()}>{user.name}</Link></li>
                        )}
                    </ul>
                </div>
                <div className="col-sm-4">
                    <Outlet />
                </div>
            </div>
            </>
   
    )
}

export default Users;

Some points to note here are-

  1. Bootstrap5 is used here for styling.
  2. In the code a hardcoded array holding user objects is created named DUMMY_USERS.
  3. Note how links are created for each user name while looping the user array
    <Link to={user.id.toString()}>{user.name}</Link>
    

    In each iteration of the array, id is added as the link. <Link> by default takes the path relative to route and the current route is “/users” which becomes “/users/CURRENT_ID” when the link is clicked. This path is matched by the route “/users/:userId”.

  4. Note the use of <Outlet /> in Users component to render the child route’s element.
    <div className="col-sm-4">
      <Outlet />
    </div>
    

src\components\Routes\UserDetails.js

import { useParams } from "react-router-dom"
import { DUMMY_USERS } from "./Users"

const UserDetails = () => {
    
    const params = useParams();
    // Find the passed ID in the DUMMY_USERS array
    // converting params.userId to number 
    const user = DUMMY_USERS.find(user => user.id === +params.userId)
    return (
        <>
            <h2>User Details</h2>
            <div className="row">
                <div className="col-xs-6">
                    <span>User Name: </span>{user.name}
                </div>
            </div>
            <div className="row">
                <div className="col-xs-6">
                    <span>Age: </span>{user.age}
                </div>

            </div>
        </>
    )
}

export default UserDetails;

Some points to note here are-

  1. useParams() hook is used here to get the value of the dynamic segment.
  2. User whose details are to be displayed is then searched in the array using the passed id.

Please refer this post- Setting Error Page (404 Page) in React Router to get code of other components like Navigation, ErrorPage, Home, About.

When you click on Users menu

When you click on the user name, it should show the corresponding user details next to it.

child route in react

That's all for the topic Nested Route in React. If something is missing or you have something to share about the topic please write a comment.


You may also like

Thursday, November 16, 2023

Dynamic Route in React

In this post we'll learn about dynamic routes in React which includes how to set route parameters and how to fetch the route parameters.

Why dynamic routing in React

It's a very common requirement in web applications to add a route parameter to the URL based on user input or based on some events. For example, you display list of user names and you show the details of the user whose name is clicked and for that you want to pass userId as a route parameter by appending it to the path- /users/1 or /users/2 and so on based on the clicked user.

It is practically impossible to create static routes by having hard coded values in above mentioned scenario as the number of user records may vary. In such scenarios you will create dynamic routes by having a dynamic segment in your route path that acts as a placeholder for the actual value passed.

How to create dynamic route using react-router

To create a dynamic route that has a route parameter, specify the dynamic segment by prefixing it with a colon. So, the route definition will be in the following form

/route/:routeparam

For example, if you want to create a dynamic path by adding userID of the selected user then such a dynamic route can be defined as-

{path: "/users/:userId", element: <UserDetails/>}

If there is a path segment starting with ":" then it becomes a dynamic segment. In our example ":/userId" is the dynamic segment and it can match any value for this specific segment. Any URL like /users/1, /users/2, users/100 will be matched by this path pattern ("/users/:userId") and use the component UserDetails.

You can also have multiple dynamic segments in one route path- /route/:param1/:param2/:param3

How to retrieve route parameters

When a dynamic route matches the URL, the dynamic segment will be parsed from the URL and provided as params. There is a useParams() hook in react-router-dom that can be used to get values of dynamic segments in route path. The useParams() hook returns an object of key/value pairs of the route parameters from the current URL that were matched by the <Route path>.

For example if /users/100 matches the route path /users/:userId then useParams() hook will return an object as {userId:100}

You can get the whole object initially

const params = useParams();

And then get the specific route parameter when required.

params.userId

Or you can use object destructuring to get the userId param from the URL

let { userId } = useParams();

Dynamic routing ReactJS example

In the example we display a page with list of user names using Users Component. For the user's name that is clicked user details are displayed using UserDetails component. Dynamic routing is used here to pass userId as route parameter.

Route Definition

src\components\Routes\route.js

import { createBrowserRouter } from "react-router-dom";
import About from "./About";
import ErrorPage from "./ErrorPage";
import Home from "./Home";
import Navigation from "./Navigation";
import UserDetails from "./UserDetails";
import Users from "./Users";

export const router = createBrowserRouter([
    {path: "/", element: <Navigation />, errorElement: <ErrorPage />,
     children: [
        {index: true, element: <Home /> },
        {path: "/users", element: <Users />},
        {path: "/users/:userId", element: <UserDetails/>},
        {path: "about", element: <About />}
     ]
    },        
])

Notice the path with dynamic segment- {path: "/users/:userId", element: <UserDetails/>}

Providing the routes

Provide the route definition to your application using the <RouteProvider> component.

import { RouterProvider } from 'react-router-dom';
import { router } from './components/Routes/route';

function App() {
  return <RouterProvider router={router}></RouterProvider>
}

export default App;

Navigation Menu

src\components\Routes\Navigation.js

import { NavLink, Outlet } from "react-router-dom"
import "./navigation.css";

const Navigation = () => {
    return(
        <>
            <nav id="menu" className="navbar navbar-expand-lg bg-dark navbar-dark">
                <div className="container-fluid">
                    <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                        <span className="navbar-toggler-icon"></span>
                    </button>

                    <div className="collapse navbar-collapse" id="navbarNav">
                        <ul className="navbar-nav">
                            <li className="nav-item">
                                <NavLink 
                                    to="/" 
                                    className={({ isActive }) => isActive ? "active" :""} 
                                    end
                                >
                                    Home
                                </NavLink>
                            </li>
                            <li className="nav-item">
                                <NavLink 
                                    to="/users"
                                    className={({ isActive }) => isActive ? "active" :""} 
                                >
                                    Users
                                </NavLink>
                            </li>
                            <li className="nav-item">
                                <NavLink 
                                    to="/about"
                                    className={({ isActive }) => isActive ? "active" :""} 
                                >
                                    About
                                </NavLink>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
            <div className="container">
                <div className="row mt-2">
                    <div className="col-xs-12">
                        <Outlet />
                    </div>
                </div>
            </div>
        </>
    );
}

export default Navigation;

src\components\Routes\navigation.css

#menu a:link,
#menu a:visited {
    color: gray;
}
#menu a:hover {
    color: white;
}
#menu a.active {
    color:#ebecf0;
}

#menu a {
    text-decoration: none;
}

#menu ul {
    gap: 1rem;
}

Components

Two components that we need for user are Users and UserDetail.

src\components\Routes\Users.js

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

export const DUMMY_USERS = [
    {id: 1, name: "Ram", age: 23},
    {id: 2, name: "Namita", age: 25},
    {id: 3, name: "Varun", age: 32},
    {id: 4, name: "Leo", age: 28},
    {id: 5, name: "Melissa", age: 27},
]

const Users = () => {
    return(
        <>
            <div className= "row">
                <div className="col-sm-4">
                    <h2>Users</h2>
                    <ul className="list-group">

                        {DUMMY_USERS.map(user =><li className="list-group-item" key={user.id}> 
                            <Link to={`/users/${user.id.toString()}`}>{user.name}</Link></li>
                        )}
                    </ul>
                </div>
            </div>
            </>
   
    )
}

export default Users;

Some points to note here are-

  • Bootstrap is used here for styling.
  • In the code a hardcoded array holding user objects is created named DUMMY_USERS.
  • Note how links are created for each user name while looping the user array
    <Link to={`/users/${user.id.toString()}`}>{user.name}</Link>
        
    After “/users”, id is appended as another path segment.
  • When user name is clicked, path is matched by the “/users/:userId” route and UserDetails component is used for rendering.

src\components\Routes\UserDetails.js

import { useParams } from "react-router-dom"
import { DUMMY_USERS } from "./Users"

const UserDetails = () => {
    
    const params = useParams();
    // Find the passed ID in the DUMMY_USERS array
    // converting params.userId to number 
    const user = DUMMY_USERS.find(user => user.id === +params.userId)
    return (
        <>
            <h2>User Details</h2>
            <div className="row">
                <div className="col-xs-6">
                    <span>User Name: </span>{user.name}
                </div>
            </div>
            <div className="row">
                <div className="col-xs-6">
                    <span>Age: </span>{user.age}
                </div>

            </div>
        </>
    )
}

export default UserDetails;

Some points to note here are-

  • useParams() hook is used here to get the value of the dynamic segment.
  • User whose details are to be displayed is then searched in the array using the passed id.

Please refer this post- https://www.knpcode.com/2023/10/setting-error-page-react-router.html to get code of other components like ErrorPage, Home. About.

When Users menu is clicked

Dynamic route in React

Clicking on user name takes to the User details page with details displayed for the user name that was clicked

useParams() in React

Nested routes provide a better way to do the same thing. check this post- Nested Route in React

That's all for the topic Dynamic Route in React. If something is missing or you have something to share about the topic please write a comment.


You may also like

Sunday, October 29, 2023

Setting Error Page (404 Page) in React Router

In this article we'll see how to show an error page (404 page not found) with React Router.

Anytime your app throws an error while rendering, loading data, or performing data mutations, React Router will catch it and render an error screen. Default error screen in React Router is shown below.

Default error page

You can create your own custom error page that should be displayed in case of any error.

Note in this article error page is created using the React Router V6.4 element 'errorElement' and the useRouteError() hook. This feature works only if you are using a data router like createBrowserRouter.

Creating error page component

If your app throws an error while rendering, loading data, or performing data mutations instead of the normal render path for your Routes (<Route element>), the error path will be rendered (<Route errorElement>) and the error made available with useRouteError.

In our error page we can use useRouteError() hook to access error and show message using that error object.

src\components\Routes\ErrorPage.js

This is the error page displayed in case of any error.

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

const ErrorPage = () => {
    const error = useRouteError();
    //console.log(error);
    return (
        <div>
          <p style={{color: "red", fontSize:"20px"}}>
            
            {error.status === 404 ? "404 Page Not Found" : ""}
            <br />
            {error.data}
          </p>
        </div>
    );
}

export default ErrorPage;

Since you have access to error object you can check the error status and return appropriate message as done here for '404' error status.

Setting errorPage using errorElement

src\components\Routes\route.js

import { createBrowserRouter } from "react-router-dom";
import About from "./about";
import ErrorPage from "./ErrorPage";
import Home from "./home";
import Navigation from "./navigation";

export const router = createBrowserRouter([
    {path: "/", element: <Navigation />, errorElement: <ErrorPage />,
     children: [
        {index: true, element: <Home /> },
        {path: "/about", element: <About />}
     ]
    },        
])

Notice the configuration of errorPage using errorElement in the parent route. You can also use the errorElement with specific routes.

Keeping errorElement with the parent route works for all the routes because errors will bubble up through parent routes when a route does not have an errorElement. Putting an errorElement at the top of your route tree gives you an opportunity to handle nearly every error in your app in one place.

Trying to access a non-existent page.

Error page in React Router

Please refer this post- React Router - NavLink in react-router-dom to get code for other Components like Navigation, Home and About.

That's all for the topic Setting Error Page (404 Page) in React Router. If something is missing or you have something to share about the topic please write a comment.


You may also like

Wednesday, October 25, 2023

Index Route in React Router

In this tutorial we'll see what is index route in react router.

Index routes in react-router

In most of the cases you'll have a default child route matching the parent route's exact path.

For example, in the following route definition you can notice one parent route with path as "/" and also a child route with the same path as "/".

export const router = createBrowserRouter([
    {path: "/", element: <Navigation />,
     children: [
        {path: "/", element: <Home /> },
        {path: "/about", element: <About />}
     ]
    },        
])

In such cases you can configure child route as an index route. That tells the router to match and render this route when the user is at the parent route's exact path.

All you have to do is use { index:true } instead of { path: "" } to configure a route as an index route.

Index route React example

We'll use the same example as used in the post- React Router - NavLink in react-router-dom

Only change that is needed is in src\components\Routes\route.js

import { createBrowserRouter } from "react-router-dom";
import About from "./about";
import Home from "./home";
import Navigation from "./navigation";

export const router = createBrowserRouter([
    {path: "/", element: <Navigation />,
     children: [
        {index: true, element: <Home /> },
        {path: "/about", element: <About />}
     ]
    },        
])

In the child route for Home page instead of path, index: true is used to make it an index route so that it becomes a default child route. Whenever user is at the parent route's exact path this default child route is matched.

That's all for the topic Index Route in React Router. If something is missing or you have something to share about the topic please write a comment.


You may also like

Monday, October 9, 2023

React Router - NavLink in react-router-dom

In the post React Router - Link in react-router-dom we saw how you create navigational links in React routing. If you are using a framework like Bootstrap for styling with <Link> it works fine and you will have proper space between links, active link and non-active link styling will also be taken care of. But you may want more control over styling of links and that is possible with <NavLink> in React Router.

<NavLink> in React Router

Navlink is another way to create link which provides some extra functionalities. With NavLink you have the capability to know whether link is in "active" or "pending" state. This is useful when building a navigation menu where you want to highlight the currently selected menu item.

Navlink also provides useful context for assistive technology like screen readers.

How to get menu state information

The className prop used with NavLink takes a function which returns a css class name that should be added for styling. This function also receives an object which you can destructure to get isActive and isPending property.

These properties are of type Boolean. If current link is active then isActive has the value true otherwise value is false.

<NavLink
  to="/home"
  className={({ isActive, isPending }) =>
    isPending ? "pending" : isActive ? "active" : ""
  }
>
  Home
</NavLink>

An active class is also added to a <NavLink> component, when it is active, by default. So you can use CSS to style it.

Navigation menu using NavLink - React Example

Let's first create a navigation menu page

src\components\Routes\navigation.js

import { NavLink, Outlet } from "react-router-dom"
import "./navigation.css";

const Navigation = () => {
    return(
        <>
            <nav id="menu" className="navbar navbar-expand-lg bg-dark navbar-dark">
                <div className="container-fluid">
                    <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                        <span className="navbar-toggler-icon"></span>
                    </button>

                    <div className="collapse navbar-collapse" id="navbarNav">
                        <ul className="navbar-nav">
                            <li className="nav-item">
                                <NavLink 
                                    to="/" 
                                    className={({ isActive }) => isActive ? "active" :""} 
                                    end
                                >
                                    Home
                                </NavLink>
                            </li>
                            <li className="nav-item">
                                <NavLink 
                                    to="/about"
                                    className={({ isActive }) => isActive ? "active" :""} 
                                >
                                    About
                                </NavLink>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
            <Outlet />
        </>
    );
}

export default Navigation;

As you can see with NavLink there is a function to check if isActive property is true or not. If it is true then active class is added.

src\components\Routes\navigation.css

#menu a:link,
#menu a:visited {
    color: gray;
}
#menu a:hover {
    color: white;
}
#menu a.active {
    color:#ebecf0;
}

#menu a {
    text-decoration: none;
}

#menu ul {
    gap: 1rem;
}

Route Definition

src\components\Routes\route.js

import { createBrowserRouter } from "react-router-dom";
import About from "./about";
import Home from "./home";
import Navigation from "./navigation";

export const router = createBrowserRouter([
    {path: "/", element: <Navigation />,
     children: [
        {path: "/", element: <Home /> },
        {path: "/about", element: <About />}
     ]
    },        
])

Providing the routes

Provide the route definition to your application using the <RouteProvider> component.

import { RouterProvider } from 'react-router-dom';
import { router } from './components/Routes/route';

function App() {
  return <RouterProvider router={router}></RouterProvider>
}

export default App;

Components

src\components\Routes\home.js

const Home = () => {
    return (
        <>
            <h2>This is home page</h2>
        </>
    )
}

export default Home;

src\components\Routes\about.js

const About = () => {
    return <h2>This is a router demo</h2>
}
export default About;

When Home is clicked

NavLink in react-router-dom

When About is clicked

NavLink react example

end prop in NavLink

There is also an end prop used with NavLink to change the matching logic for the active and pending states to only match to the "end" of the NavLink's to path. Without using 'end' any URL that has path given in "to" within it will be matched even if path is longer. With 'end' it is an exact match, If the URL is longer than to, it will no longer be considered active.

For example, without using end; link <NavLink to="/tasks" /> will be matched for both '/tasks' and '/tasks/123' resulting in ‘isActive’ being true in both cases.

With this link where 'end' is also used- <NavLink to="/tasks" end /> isActive will be true only for '/tasks' not for '/tasks/123'

Using end with root route

As per react-router documentation you don't need to add end with root route so <NavLink to="/" end> is not required.

“<NavLink to="/"> is an exceptional case because every URL matches /. To avoid this matching every single route by default, it effectively ignores the end prop and only matches when you're at the root route.”

That's all for the topic React Router - NavLink in react-router-dom. If something is missing or you have something to share about the topic please write a comment.


You may also like

Installing Bootstrap in React

In this post we'll see how to add Bootstrap library to Reactjs.

Bootstrap is one of the most popular feature-packed frontend toolkit for developing responsive, mobile-first application. There are several pre-styled components provided by Bootstrap to be used as it is.

Installing Bootstrap in React application

Assuming you have already created a React project using create-react-app just go to the project folder and run the following command to install Bootstrap.

npm install bootstrap

If you are using yarn then

yarn add bootstrap

Note that using the above command installs the latest Bootstrap version. If you want to install specific version then specify it with @.

npm install bootstrap@4.6.2

Verify the bootstrap installation

You can go to the package.json and there you should see the entry for bootstrap in the dependency section if it is installed.

"dependencies": {
    "@reduxjs/toolkit": "^1.9.5",
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "bootstrap": "^5.3.0",
    "cors": "^2.8.5",
    "express": "^4.18.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-redux": "^8.1.1",
    "react-router-dom": "^6.16.0",
    "react-scripts": "5.0.1",
    "redux": "^4.2.1",
    "web-vitals": "^2.1.4",
    "ws": "^8.13.0"
  },

Include Bootstrap's CSS and JS

In order to use Bootstrap you also need to import it in the components where it is needed. Rather than doing it in each component separately, it is better to import it in index.js file so that it is available to all the components.

import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.bundle.min.js';

Add these two imports in src\index.js to add minified css file and JavaScript bundle (bundle includes Popper for positioning dropdowns, poppers, and tooltips)

You can also include Popper and Bootstrap's JS separately.

import '@popperjs/core/dist/umd/popper.min.js';
import 'bootstrap/dist/js/bootstrap.min.js';

After that you can use Bootstrap for styling in your components.

Here is a simple example with changes in App.js

function App() {
  return (
    <div className="container">

      <div className="row">
        <div className="col-xs-12">
          <h1>Using Bootstrap</h1>
          <p>Just to check Bootstrap integration in React app</p>
        </div>
      </div>
      <button className="btn btn-primary">Click Me</button>
     </div> 
  );
}

export default App;

That's all for the topic Installing Bootstrap in React. If something is missing or you have something to share about the topic please write a comment.


You may also like