0

I am trying to :

  1. generate radio buttons from a constant array using Map in react
  2. let user select one and set the state with handleChange()

With the following code I was able to achieve 1, but for some reason when I try to display with handleChange() I see it is an empty string.

Could you please help me ?

Thanks

import React, { Component } from "react";

const members = ["Araki", "Ibata", "Fukutome", "Woods", "Alex", "Tatsunami"];

export default class MyRadio extends Component {
  constructor(props) {
    super(props);

    this.state = {
      lastName: "",
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    console.log("handleChange() e:" + e.target.value);

    this.setState({
      [e.target.name]: e.target.value,
    });
  }
 

  render() {
    console.log("render");
    return (
      <form>
        <div>
          {members.map((item) => (
            <React.Fragment>
              <label htmlFor={item.name}> {item}</label>
              <input
                name="lastName"
                key={item.name}
                id={item.name}
                value={item.name}
                type="radio"
                onChange={this.handleChange}
              />
            </React.Fragment>
          ))}
        </div>
        <div></div>
      </form>
    );
  }
}

1 Answer 1

1

To make this workable solution you have to change the members as follow

const members = [{name: "Araki", name: "Ibata", ...}];

array should be a object array with each object has name property because in the map you are expecting name should be there as item.name.

Or either you have to change the loop without item.name you have to use item

{members.map((item) => (
    <React.Fragment>
          <label htmlFor={item}> {item}</label>
          <input
            name="lastName"
            key={item}
            id={item}
            value={item}
            type="radio"
            onChange={this.handleChange}
          />
    </React.Fragment>
))}
Sign up to request clarification or add additional context in comments.

2 Comments

After trying out I see this warning: Warning: Each child in a list should have a unique "key" prop. It's weird because I set key = {item}
key sohuld be in react.fragment

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.