Lifting the State Up
Membuat Lebih dinamis tombol dan munculkan data nya ke navbar
App.js
import React, {Component} from "react";
import Navbar from "./components/Navbar";
import Counters from "./components/Counters";
import './App.css';
class App extends Component {
state = {
counters: [
{ id: 1, value: 4 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
]
};
handleIncrement = counter => {
// console.log(counter)
const counters = [...this.state.counters];
const index = counters.indexOf(counter);
counters[index] = {...counter};
counters[index].value++;
this.setState({ counters });
// console.log(this.state,counters[index]);
}
handleReset = () => {
const counters = this.state.counter.map(c => {
c.value = 0;
return c;
})
this.setState({ counters })
}
handleDelete = (counterId) => {
const counters = this.state.counters.filter(c => c.id !== counterId);
this.setState({ counters })
// console.log('event delete', counterId)
}
render() {
return (
<>
<Navbar totalCounters={this.state.counters.filter(c => c.value > 0).length} />
<main className="container">
<Counters
counters={this.state.counters}
onReset={this.handleReset}
onIncrement={this.handleIncrement}
onDelete={this.handleDelete}
/>
</main>
</>
);
}
}
export default App;
Counter.jsx
import React, { Component } from 'react';
class Counter extends Component {
render() {
return(
<div>
<span className={this.getBadgeClasses()}>{this.formatCount()}</span>
<button onClick={() => this.props.onIncrement(this.props.counter)} className="btn btn-secondary btn-sm">Increment</button>
<button onClick={() => this.props.onDelete(this.props.counter.id)} className="btn btn-danger btn-sm m-2">Delete</button>
</div>
)
}
getBadgeClasses() {
let classes = "badge m-2 badge-";
classes += this.props.counter.value === 0 ? "warning" : "primary";
return classes;
}
formatCount() {
const { value } = this.props.counter;
return value === 0 ? <h1>Zero</h1> : value;
}
}
export default Counter
Counters.jsx
import React, { Component } from "react";
import Counter from "./Counter";
class Counters extends Component {
render() {
return (
<div className="container">
<button onClick={this.props.onReset} className="btn btn-primary btn-sm m-2">Reset</button>
{ this.props.counters.map(counter => (
<Counter
key={counter.id}
onDelete={this.props.onDelete}
onIncrement={this.props.onIncrement}
counter={counter}>
</Counter>
)) }
</div>
)
}
}
export default Counters
Navbar.jsx
import React, {Component} from "react";
class Navbar extends Component {
render() {
return (
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<a className="navbar-brand" href="#">
Test
<span className="badge badge-pill badge-secondary">
{this.props.totalCounters}
</span>
</a>
</nav>
)
}
}
export default Navbar
Last updated
Was this helpful?