Get the selected seats to Parent in Reactjs

Viewed 40

I have 2 components.

  • seatBooking(parent => Class Component)
  • theater(child => functional Component)

Now in the theater component, there are few checkboxes. All I want to know is when these checkboxes are clicked how do I pass the name of the selected checkbox names into an array in the parent component. following is my code

Parent

import theater from './theater ';
export default class seatBooking extends Component{
render(){
 return(
  <theater />
 )
}
}

Child

export default function theater(){
var seats = []
const [seatChecked, setSeatChecked ] = useState(false);
const handleOnChange = (e) => {
        let isChecked = e.target.checked;
        seats.push(e.target.name)
        if(isChecked){
            alert(seats);
        }else{
            seats = seats.filter((name) => e.target.name !== name);
            alert("removed",e.target.name)
        }
    console.log(seats)
}
render()
return(
        <input type="checkbox" id="c3" name="A3" 
checked={seatChecked["c3"]} onChange={(e) => handleOnChange(e)}/> 
    )}
1 Answers

You need to pass a function to your child component and maintain a state in parent for tracking the array. Here is the below modified working versions of your code.

Parent

import React from "react";
import Theater from "./Theater";
export default class SeatBooking extends React.Component {
  state = { arr: [] };

  assignMyState = (data = []) => {
    this.setState({ arr: data });
    console.log(this.state);
  };

  render() {
    return (
      <>
        <Theater handleMyState={this.assignMyState} />
      </>
    );
  }
}

Child

import { useState } from "react";

export default function Theater({ handleMyState }) {
  var seats = [];
  const [seatChecked, setSeatChecked] = useState(false);

  const handleOnChange = (e) => {
    let isChecked = e.target.checked;
    seats.push(e.target.name);
    if (isChecked) {
      alert(seats);
    } else {
      seats = seats.filter((name) => e.target.name !== name);
      alert("removed", e.target.name);
    }
    // modified
    handleMyState(seats);
    // console.log(seats);
  };

  return (
    <input
      type="checkbox"
      id="c3"
      name="A3"
      checked={seatChecked["c3"]}
      onChange={(e) => handleOnChange(e)}
    />
  );
}

NOTE: The class name and the function component should generally be in Pascal Case as a convention.

Related