Hello friends, welcome back to my blog. Today in this blog post, I am going to show you, Reactjs Update Array Value Using useState Hook.
Post working: Guy’s in this post, I am using react hook useState . By using hook useState, I am updating array values. Guy’s I must say this is very interesting. I will come with more example like this using react hooks.
For reactjs new comers, please check the below link:
Friends now I proceed onwards and here is the working code snippet and please use this carefully to avoid the mistakes:
1. Firstly, we need fresh reactjs setup and for that, we need to run below commands into out terminal and also we should have latest node version installed on our system:
npx create-react-app reacthooks cd reacthooks npm start
2. (Optional, I have used for better looks of table)Now we need to run below commands into our project terminal to get bootstrap and related modules into our reactjs application:
npm install bootstrap --save npm start //For start project again
3. Finally for the main output, we need to add below code into our reacthooks/src/App.js file or if you have fresh setup then you can replace reacthooks/src/App.js file code with below code:
import {React, useState} from 'react'; import 'bootstrap/dist/css/bootstrap.min.css' export default function App() { //Demo data const initial_data = [{ name: 'Audi', type: 'sedan' }, { name: 'BMW', type: 'sedan' }]; const [cars, setCars] = useState(initial_data) //New data value let newCar = { name: 'Benz', type: 'sedan' } //array merging const updatedCarsArray = [...cars, newCar]; console.log(updatedCarsArray); function newData() { //new array on button click setCars(updatedCarsArray); } return ( <div class="container text-center mt-5 mb-5"> Therichpost.com <table class="table table-hover table-bordered p-5"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Type</th> </tr> </thead> <tbody> { // calling state variable data to filter data inside table cars.map(function({name, type}){ return ( <tr> <td>{name}</td> <td>{type}</td> </tr> ); })} </tbody> </table> <button className="btn btn-primary" onClick={newData}>Add New Value</button> </div> ); }
Now we are done friends. If you have any kind of query or suggestion or any requirement then feel free to comment below.
Note: Friends, I just tell the basic setup and things, you can change the code according to your requirements.
I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad.
Jassa
Thanks
Recent Comments