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,970 questions

51,912 answers

573 users

How to use multiple components in React JS

1 Answer

0 votes
// src/components/counter.jsx

import React, { Component } from "react";

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

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

  render() {
    return (
      <React.Fragment>
        <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/components/multiplecounters.jsx

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

class MultipleCounters extends Component {
    state = {  }
    render() { 
        return ( 
            <div>
                <Counter />
                <Counter />
                <Counter />
            </div>
         );
    }
}
 
export default MultipleCounters;
// 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:

Render Dynamically With bootstrap.css: 13
Render Dynamically With bootstrap.css: 14
Render Dynamically With bootstrap.css: 15

{id: 8364}
{id: 8364}
{id: 8364}
{id: 8364}
{id: 8364}
{id: 8364}

*/


 



answered Apr 1, 2020 by avibootz

Related questions

2 answers 244 views
2 answers 373 views
1 answer 275 views
275 views asked Jun 17, 2020 by avibootz
2 answers 314 views
...