0

I have the following component that shows the options of a quiz, when the user select a value I want to pass the "item.id" selected in the "handleNext", no código abaixo aparece o seguinte erro:

Uncaught ReferenceError: item is not defined

code:

render () {
    return (
        <UserContext.Provider value={this.state}>
            <UserContext.Consumer>
                {({ current_statement, current_alternative, handleNext}) => (

                   <form>
                        <p>{current_statement}</p>

                        {this.state.current_alternative.map(item => (
                            <React.Fragment key={item.id}>
                                <div>
                                    <input id={item.id} type="radio" name="question"/>
                                    <label htmlFor={item.id}>{item.content}</label>
                                </div>
                            </React.Fragment>
                        ))}

                        <button onClick={(e) => this.handleNext(e, item.id)} type="button">Next</button>

                    </form>
                )}

            </UserContext.Consumer>
        </UserContext.Provider>
    )
}
Hiago Bonamelli
  • 371
  • 5
  • 15

2 Answers2

1

The problem is your binding of your Next button:

this.handleNext(e, item.id)

You've added this OUTSIDE of your .map() function, so there is no item (This is explicitly defined on each loop of your this.state.current_alternative map). Move this inside of the .map() array, and you'll be able to access item.

Blue
  • 22,608
  • 7
  • 62
  • 92
1
  handleRadioChange = id => this.setState({selected: id})

  render() {
    ...
    <input id={item.id} type="radio" name="question" onChange={e => this.handleRadioChange(e.event.target.id)} />
    ...

    <button onClick={(e) => this.handleNext(e, this.state.selected)} type="button">Next</button>

In short: You have to store selected id of radio button selected by user in state, then your button will take id from state when the user presses it.

Blue
  • 22,608
  • 7
  • 62
  • 92
Nikko Khresna
  • 1,024
  • 8
  • 10