1

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>
        );
    }
}
Ivaldir
  • 185
  • 12
  • 1
    Does this answer your question? [ReactJS bind(this)](https://stackoverflow.com/questions/47957741/reactjs-bindthis) - Your problem is at `onChange={this.handleChange}`, not when passing props. – Sergiu Paraschiv May 04 '21 at 13:50
  • The [React event handling docs](https://reactjs.org/docs/handling-events.html) cover this. It's usually worth taking a spin through framework docs :) – Dave Newton May 04 '21 at 14:40

1 Answers1

1

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);
    };
samuei
  • 1,949
  • 1
  • 10
  • 26