Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

How to update the state in React JS

2 Answers

0 votes
// src/components/multiplecounters.jsx

import React, { Component } from "react";
import Counter from "./counter";

class MultipleCounters extends Component {
  state = {
    counters: [
      { id: 1, cvalue: 3 },
      { id: 2, cvalue: 1 },
      { id: 3, cvalue: 7 }
    ]
  };

  // Handle event - update the state
  deleteCounter = id => {
    const newState = this.state.counters.filter(cr => cr.id !== id);
    this.setState({ counters: newState });
  };

  render() {
    return (
      <div>
        {this.state.counters.map(mcounter => (
          // Pass data
          <Counter
            key={mcounter.id}
            // Pass reference of the function to child component: Counter
            onDelete={this.deleteCounter}
            // Pass state id and cvalue to: Counter
            mcounter={mcounter}
          />
        ))}
      </div>
    );
  }
}

export default MultipleCounters;
// src/components/counter.jsx

import React, { Component } from "react";

class Counter extends Component {
  state = {
    total: this.props.mcounter.cvalue
  };

  totalPlus = e => {
    console.log(e);
    // Update the state
    this.setState({ total: this.state.total + 1 });
  };

  render() {
    console.log(this.props);
    return (
      <div>
        <h5>Counter Number: {this.props.id}</h5>
        <span className={this.setStyle()}>
          Render Dynamically With bootstrap.css: {this.getTotal()}
        </span>
        {/* Pass event argument */}
        <button
          onClick={() => this.totalPlus({ id: 8364 })}
          className="btn btn-secondary btn-sm"
        >
          +
        </button>
        {/* Raise event */}
        <button
          onClick={() => this.props.onDelete(this.props.mcounter.id)}
          className="btn btn-danger btn-sm m-2"
        >
          Del
        </button>
      </div>
    );
  }

  setStyle() {
    let classes = "badge m-2 badge-";
    classes += this.state.total === 0 ? "warning" : "primary";
    return classes;
  }

  getTotal() {
    const { total } = this.state;
    return total === 0 ? "Zero" : total;
  }
}

export default Counter;
// src/index.js 

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.css';
import MultipleCounters from './components/multiplecounters'


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

serviceWorker.unregister();



/*
run:

{id: 8364}
{mcounter: {…}, onDelete: ƒ}
{id: 8364}
{mcounter: {…}, onDelete: ƒ}

deleteCounter()
deleteCounter()
deleteCounter()

*/

 



answered Apr 2, 2020 by avibootz
0 votes
// counter.jsx

import React, { Component } from "react";

class Counter extends Component {
  state = {
    total: 12
  };

  // Bind with arrow function
  totalPlus = () => {
    // Update the state 
    this.setState({total: this.state.total + 1});
  }

  render() {
    return (
      <React.Fragment>
        <span className={this.setStyle()}>
          Render Dynamically With bootstrap.css: {this.getTotal()}
        </span>
        <button onClick={this.totalPlus} className="btn btn-secondary btn-sm">
          +
        </button>
      </React.Fragment>
    );
  }

  setStyle() {
    let classes = "badge m-2 badge-";
    classes += this.state.total === 0 ? "warning" : "primary";
    return classes;
  }

  getTotal() {
    const { total } = this.state;
    return total === 0 ? "Zero" : total;
  }
}

export default Counter
// index.js 

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import 'bootstrap/dist/css/bootstrap.css';
import Counter from './components/counter'


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

serviceWorker.unregister();




/*
run:

ender Dynamically With bootstrap.css: 13

*/

 



answered May 4, 2024 by avibootz

Related questions

...