Ivaldir
Ivaldir

Reputation: 195

Passing react function as props

I've been looking around at other post but haven't found what is wrong with my code. It should pass a function down to the component as a prop, however I have dificulties accessing it as when I do I get the response that the it cannot read props of undefined. What am I doing wrong?

Props:

<SettingsSection    forceUpdateHandler = {this.props.forceUpdateHandler}
                                        languages = {this.props.languages}
                                        setLanguage = {this.props.setLanguage}
                                        getLanguage = {this.props.getLanguage}
                                        getParameters = {this.props.getParameters}/>

Component:

class SettingsSection extends Component{

    constructor(props){
        super(props)
        this.state = {
            value: "java"
        }
    }

    // Send change in component upwards.
    handleChange(event) {
        this.props.setLanguage(event.target.value);
    }

    // Render component.
    render() {
        return (
            <div>
                {/*settings section will be changed later*/}
                <h5 style={{paddingTop:"20px"}}>Settings</h5>

                {/* Language drop down menu */}
                <h6 style={{paddingTop:"15px"}}>Export Language</h6>
                <select style={{paddingTop:"5px"}} onChange={this.handleChange} value={this.state.value}>
                    {this.props.languages.map(language => { return ( <option value={language}> {language} </option>)})}
                </select>
            </div>
        );
    }
}

Upvotes: 1

Views: 44

Answers (1)

samuei
samuei

Reputation: 2102

this is undefined in your function. Since undefined doesn't have any props, you can't access .props of it.

You need to bind it to the component in your constructor, like so:

constructor(props){
        super(props)
        this.state = {
            value: "java"
        }
        this.handleChange = this.handleChange.bind(this);
    };

Upvotes: 1

Related Questions