// 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 }
]
};
render() {
return (
<div>
{this.state.counters.map(mcounter => (
// Pass data
<Counter key={mcounter.id} cvalue={mcounter.cvalue}>
{ /* Pass children to element between open and close tags */ }
<h5>Counter: {mcounter.id}</h5>
</Counter>
))}
</div>
);
}
}
export default MultipleCounters;
// src/components/counter.jsx
import React, { Component } from "react";
class Counter extends Component {
state = {
total: this.props.cvalue
};
totalPlus = (e) => {
console.log(e);
this.setState({ total: this.state.total + 1 });
};
render() {
console.log(this.props);
return (
<React.Fragment>
{this.props.children}
<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>
</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;
// 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:
Counter: 1
Render Dynamically With bootstrap.css: 4
Counter: 2
Render Dynamically With bootstrap.css: 2
Counter: 3
Render Dynamically With bootstrap.css: 8
{id: 8364}
{cvalue: 1, children: {…}}
{id: 8364}
{cvalue: 7, children: {…}}
{id: 8364}
{cvalue: 7, children: {…}}
*/