skip to Main Content

I try to use a prop value to set a state but it keeps giving me null. The prop value has a valid
value (boolean).

This is the constructor of the child component:

constructor(props: any) {
        super(props);
        this.setState({
            ...this.state,
            customUser: props.customUser,
            open: props.open
        })
    }

If I log the prop it will give the value true, as I want. But when this value is used to set the state in the constructor. It will return null here and not render:

render() {
        return (
here  --->    <Dialog open={this.state.open}>
                <DialogTitle>Account Delete</DialogTitle>
                <DialogContent>
                    <p>Are you sure you want to delete your account?</p>
                </DialogContent>
                <DialogActions>
                    <Button variant="contained" color="primary" onClick={() => {
                    }}>Yes</Button>
                    <Button variant="contained" color="secondary" onClick={() => {this.toggleDialog}}>No</Button>
                </DialogActions>
            </Dialog>
        )
    }

I tried using a different named state to set the prop value to. But this didn’t work either.

2

Answers


  1. Chosen as BEST ANSWER

    As the response of Andy Ray said, I used setState instead of this.state. Replacing this fixed my issue. Thanks!


  2. Try to do it with componentDitMount (or useEffect with newer version).

    componentDidMount() {
      const { open } = this.props;
      this.setState({
        ...this.state,
        customUser: this.props.customUser,
        open: open || false
      });
    }
    

    You can do it like this with componentDidMount.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search