Joao Livio
Joao Livio

Reputation: 139

React change state from child component not working

After research I cannot find a way to do this, I'm missing I think a small thing, or not.

I have to change the state to false from the child component but this is not working and the real problem is I don't know why.

To show the child and hide the main I'm doing this is working

that = this;
    $('#example tbody').on('click', '.btnListEdit', function () {
      var data = table.row($(this).closest('tr')).data();
      that.setState({
        edit: true
      });
});

This is my Main React Component

public render(): React.ReactElement<ICertificatesListProps> {
    return (
      <div>
        {
          this.state.tableItems.length === 0 ?
            (
              <LinearProgress />
            ) : (
              <div>
                 {
                this.state.edit ?
                (
                  <EditCert description={undefined} context={this.props.context}  myprops={this.state} handler={this.handlerFilters} />
                ) : (

I'm passing my "myprops" to fire the Handle in this component bellow in the child component

 handlerFilters() {
    this.setState({
      edit: false
    });
  }

My child component

import * as React from 'react';

export const EditCert = (myprops) => {
    function ExitHandler() {
        myprops.handleFilters();
    }

    return (
        <div>
            <Select
                labelId="selPrintedLabel"
                id="selPrinted"
                label="Printed"
                fullWidth={true}
                variant="outlined"
            // value={this.state.selectYesNo}
            // defaultValue={this.state.selectYesNo}
            // onChange={e => this.setState({ selectYesNo: typeof e.target.value === 'string' ? e.target.value : '' })}

            >
                <MenuItem value="">
                    <em>All</em>
                </MenuItem>
                <MenuItem value={"1"}>Yes</MenuItem>
                <MenuItem value={"0"}>No</MenuItem>
            </Select>
            <Button onClick={ExitHandler} size="small" style={{ "width": "100%" }} id="fireModal" variant="contained" >Certificate labels</Button>
        </div>
    );
}

The handler for the child is not fire the state to false in order to hide my child in the main.

Please kindly provide any knowledge

Upvotes: 1

Views: 1166

Answers (1)

Arinton Akos
Arinton Akos

Reputation: 165

I guess EditCert is your child component. If yes, than your problem is that you are passing the handlerFilters function as handler to the child, but in the child component you are trying to access it by handlerFilters.

It should look like this:

function ExitHandler() {
    myprops.handler();
}

Also note that there is a typo, at first you wrote handlerFilters, in the child you wrote handleFilters.

Upvotes: 2

Related Questions