Categories

Friday, April 19, 2024
#919814419350 therichposts@gmail.com
Reactjs

Reactjs push values to state array onclick event

Reactjs push values to state array onclick event

Hello, welcome to therichpost.com. In this post, I will tell you, Reactjs push values to state array onclick event. Reactjs is a Javascript Library to build user interface.

In this post, I am playing with  input field and input button to push new values to state array . On button click, I am getting the input box value and that value, I am pushing to state array.

Here is the working image in reactjs array values:

reactjs-pust-values-state-array

Here is the working and tested code and you can add this code into your index.js file:

 

import React from 'react';
import ReactDOM from 'react-dom';

class Hello extends React.Component{
    constructor(props)
    {
      super(props);
      this.state = {addtask: '', tasks:[{name:'therichpost'}]};
      this.addValue = this.addValue.bind(this);
      this.updateInput = this.updateInput.bind(this);
    }
    
    addValue(evt)
    {
      evt.preventDefault();
        
        let tasks = this.state.tasks;
        let addtask = this.state.addtask;
        tasks.push({name:addtask});
        this.setState({tasks:tasks});
        console.log(tasks);
    }
    updateInput(evt){
      this.setState({addtask: evt.target.value}); 			
        }
    
    render()
    {
      return (
      <div>
      <h1>{this.state.value}</h1>
       <ul>
        {
        //map array data
        this.state.tasks.map(function(val){
          return <li key={val.name}>{val.name}</li>
        })
        }
        </ul>
      <input type="text" onChange={this.updateInput} /><br/><br/>
      <input type="button" value="Click Me :)" onClick={this.addValue}/>
      </div>
      )
    }
  }

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

 I will do more with reactjs. If you have any query related to this post then please comment below. 

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 14, Angular 15, Angular 16, Angular 17, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.