yevg
yevg

Reputation: 1966

React JS - Calling function passed as a prop

I am passing a function to handle the state of a modal window component from a parent component to a child component in a React app.

Parent Component

class App extends Component {

    constructor() {

        super();
        this.state = { 

            'modalVisibility' : false,
            'modalContent' : ""
        }

        this.handleModal = this.handleModal.bind(this);
    }

    handleModal(visibility, content, innerClass){

        this.setState({ 
            modalVisibility: visibility,
            modalContent: content ? content : null,
            modalClass: innerClass ? innerClass : null
        });
    }

    render() {

        return (

            <div>

                <Modal show={this.state.modalVisibility} content={this.state.modalContent} />

                <Content modal={this.handleModal} />

            </div>
        )
    }
}

Child Component

class Content extends Component {

    constructor(props) {

        super(props);

        console.log(this.props.modal); // Object { modal: handleModal() }
        this.props.modal(true,"hello modal"); // TypeError: _this.props.modal is not a function 
    }
}

The function handleModal() looks like it is successfully passed to the Content component and seems to be defined as a function, but calling it throws an error.

What am I missing here?

Upvotes: 0

Views: 6589

Answers (1)

Matt Greenberg
Matt Greenberg

Reputation: 2330

Your constructor doesn't have props bound to this. Use the props argument to access the props in the constructor function.

constructor(props) {
   super(props);
   console.log(props.modal);
   props.modal(true, 'hello modal');
}

Upvotes: 3

Related Questions