, ,

Creating a CRUD Project with React.js, Vite.js, and Context API Using useContext Hook and Bootstrap Table in Browser

Posted by


In this tutorial, we will be creating a CRUD (Create, Read, Update, Delete) application using React.js and Vite.js along with the Bootstrap Table component. We will be managing the application state using the React Context API and the useContext Hook to share the state between different components.

Before we get started, make sure you have Node.js and npm installed on your machine. You can install them from the official Node.js website if you haven’t already.

To start the project, we will first create a new React application using Vite.js. To do this, open your terminal and run the following commands:

npm init @vitejs/app react-vite-context-crud
cd react-vite-context-crud
npm install

Once the project is created, we can install the Bootstrap Table package that we will be using in our project. Run the following command in the terminal to install the Bootstrap Table package:

npm install bootstrap-table

Next, we will create a new context file where we will define our global state and provide it to the rest of the application components. Create a new file called AppContext.js in the src folder and add the following code:

import React, { createContext, useContext, useReducer } from 'react';

const initialState = {
  data: [],
};

const AppContext = createContext();

export const useAppContext = () => {
  const context = useContext(AppContext);
  if (!context) {
    throw new Error('useAppContext must be used within an AppProvider');
  }
  return context;
};

const reducer = (state, action) => {
  switch (action.type) {
    case 'ADD_DATA':
      return {
        ...state,
        data: [...state.data, action.payload],
      };
    case 'DELETE_DATA':
      return {
        ...state,
        data: state.data.filter((item) => item.id !== action.payload),
      };
    default:
      return state;
  }
};

const AppProvider = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <AppContext.Provider value={{ state, dispatch }}>
      {children}
    </AppContext.Provider>
  );
};

export default AppProvider;

In the above code, we are creating a AppContext using the createContext function and providing a custom useAppContext hook to access the state and dispatch function. We also define an initial state for our application and a reducer function to manage state changes.

Next, we will create a table component that will display the data and provide CRUD functionality. Create a new file called DataTable.js in the src folder and add the following code:

import React from 'react';
import { useAppContext } from './AppContext';

const DataTable = () => {
  const { state, dispatch } = useAppContext();

  const handleDelete = (id) => {
    dispatch({ type: 'DELETE_DATA', payload: id });
  };

  return (
    <table className="table">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        {state.data.map((item) => (
          <tr key={item.id}>
            <td>{item.id}</td>
            <td>{item.name}</td>
            <td>
              <button
                onClick={() => handleDelete(item.id)}
                className="btn btn-danger"
              >
                Delete
              </button>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
};

export default DataTable;

In the above code, we are using the useAppContext hook to access the state and dispatch function from the context. We then render a table with the data from the state and provide a delete button that dispatches a delete action to remove an item.

Finally, we need to create a form component that will allow users to add new data to the table. Create a new file called DataForm.js in the src folder and add the following code:

import React, { useState } from 'react';
import { useAppContext } from './AppContext';

const DataForm = () => {
  const { dispatch } = useAppContext();
  const [name, setName] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    dispatch({
      type: 'ADD_DATA',
      payload: { id: Date.now(), name },
    });
    setName('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Enter name"
      />
      <button type="submit" className="btn btn-primary">Add</button>
    </form>
  );
};

export default DataForm;

In the above code, we are using the useState Hook to manage the input value for the new data and dispatch an action to add it to the state when the form is submitted.

Now, we can create the main App component that will serve as the entry point for our application. Update the App.js file in the src folder with the following code:

import React from 'react';
import AppProvider from './AppContext';
import DataTable from './DataTable';
import DataForm from './DataForm';

const App = () => {
  return (
    <AppProvider>
      <h1>CRUD Application</h1>
      <DataTable />
      <DataForm />
    </AppProvider>
  );
};

export default App;

In the above code, we are wrapping our main components with the AppProvider to provide the context to the rest of the application.

Lastly, update the main.jsx file in the src folder to render the App component:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

Now, you can run your application using the following command in the terminal:

npm run dev

Open your browser and navigate to http://localhost:3000 to see the application in action. You should see a table with data and a form to add new items. You can add, delete, and view data in real-time using the Context API and the useContext Hook.

That’s it! You have successfully created a CRUD application using React.js and Vite.js with the Bootstrap Table component and the useContext Hook. You can extend this application further by adding edit functionality, sorting, pagination, or any other feature you like. Happy coding!

0 0 votes
Article Rating

Leave a Reply

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@techbeast5523
3 hours ago

worst video ever

@techbeast5523
3 hours ago

bilkul bakwas video

@techbeast5523
3 hours ago

dekh dekh ke bas coding kar raha hai kuch aata nahi hai

@robertostepic118
3 hours ago

haha 30 usd for source code. You are funny

4
0
Would love your thoughts, please comment.x
()
x