0

I'm trying to use the select tag in React. I have the following component:

class InteractionHeader extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            allDays: [],
            selected: ""
        };

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

    componentDidMount() {
        this.setState({
            allDays: ["a", "b"],
            selected: "a"
        });
    }

    dateChanged(e) {
        e.preventDefault();
        console.log(event.target.value);
    }
}

And in my render, I have the following:

render() {
    return (
        <div>
            <select value={this.state.selected} onChange={this.dateChanged}>
                {this.state.allDays.map((x) => {
                    return <option key={`${x}`} value={`${x}`}>{x}</option>
                })};
            </select>
        </div>
    );
}

However, when I select a different option, my console prints undefined instead of the option I selected. What is going on and how do I prevent it?

2
  • remove e.preventDefault() Commented Jul 18, 2018 at 18:58
  • I added an answer to it below Commented Jul 18, 2018 at 19:05

2 Answers 2

1

You are calling it wrong

dateChanged(e) {
        console.log(e.target.value);
    }

You should use prevent default in case where you donot want your page to take a refresh and try to make a server side call. In case of select there is nothing like this.

Sign up to request clarification or add additional context in comments.

Comments

0

You have a typo in dateChanged(e) method. You need to log e.target.value instead of event.target.value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.