React – Parent Child Button Select Example

Photo by Radovan Zierik from Pexels

This is an example of a parent rendering a Child Component that has a button. The button calls a function in the Parent with its unique identifier and the Parent changes the state of the buttons properties. This would be useful when you have X number of Child Components and you want to display/track which one was selected.

This example uses the React-Bootstrap button. You can install react-bootstrap with the following NPM command. Get more information about react-bootstrap here.

npm install react-bootstrap bootstrap

Parent.js

Create the Parent Component will pass the data and the button color to the Child Component. A function labeled onSelectButton will handle the button selection logic.
Warning! The onSelectButton has to be an arrow function in order to use this.setState({}).

import React, { Component } from 'react'
import Child from './Child';

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      btnArr: []
    };
  }

  onSelectButton = (id) => {
    console.log('Child ', id);
    var numArr = [];
    for (let i = 0; i < 6; i++) {
      if(i == id) {
        numArr.push({id: i, state: true, color: 'primary'});
      } else {
        numArr.push({id: i, state: false, color: 'secondary'});
      }      
    }
    this.setState({btnArr: numArr});

  }

  componentDidMount() {    
    var numArr = [];
    for (let i = 0; i < 6; i++) {
      numArr.push({id: i, state: false, color: 'secondary'})
    }
    this.setState({btnArr: numArr})
  }
  
  render() {    
    return (
      <div className="container">               
        {this.state.btnArr.map(item => (          
          <Child data={item} btnColor={item.color} onChangeVote={this.onSelectButton}></Child>
        ))}
      </div>
    );
  }
}

export default Parent;

Child.js

The Child Component just renders the button and calls onSelectButton(id) which is referenced by onChangeVote when it’s clicked.

import React from 'react';
import Button from 'react-bootstrap/Button';

class Child extends React.Component {
  constructor(props) {
    super(props);
  }

  
  voteChangeEvent = (event) => {
    this.props.onChangeVote(this.props.data.id);
  }

  
  render() {
    return (
      <React.Fragment>          
          <Button variant={this.props.btnColor} onClick={this.voteChangeEvent}>
            {this.props.data.id}
          </Button>
      </React.Fragment>
    );
    
  }
}
export default Child;

From the App.js file add the following:

import React from 'react';

import Parent from './Parent'; // Or under a folder labeled Components/demo/Parent 
function App() {
  return (
    <div className="App">
      <Router>                
        <MainNav />        
      </Router>
    </div>
  );
}

export default App;

Good Luck!

Photo by Tara Winstead from Pexels