-1

I have a react container with a form inside it. The form contains three radio buttons. I want each value for each radio button input to be an object taken from an array of objects in my reducer. However, when I console.log the value of a radio button input, I get this:

[object Object]

I know that [object Object] is the default toString representation of an object in javascript, but how can I grab the actual object so I can use the information inside of it?

here is my code:

class NoteInput extends React.Component {
    constructor(props) {
        super(props);

        this.state={
            selectedValue: null,
        }

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(e) {
        this.setState({selectedValue: e.target.value})
    }

    handleSubmit(e) {
        e.preventDefault();
        console.log(this.state.selectedValue);
    }

    render() {
        var inputs = this.props.locations.map((location, i) => {
            return (
                <div key={i}>
                    <input type="radio" id={i} name="location" value={location} />
                    <label htmlFor={'choice' + {i}}>{location.name}</label>
                </div>
            );
        });
        return (
            <div>
                <form onSubmit={this.handleSubmit} onChange={this.handleChange} >
                    {inputs}
                    <input type="submit" value="Submit" />
                </form>
            </div>
        );
    }
}

and here is my reducer:

export default function() {
    return [
        {name: 'Safa Park', locationLat: '25.184992', locationLong: '55.248140'},
        {name: 'Mercato', locationLat: '25.217054', locationLong: '55.253051'},
        {name: 'Burj Khalifa', locationLat: '25.197787', locationLong: '55.274862'}
    ]
}
user74843
  • 701
  • 2
  • 10
  • 28
  • Objects can't be used as input field values. You'll have to choose a string that identifies the object (name, index in array, ...) – JJJ Dec 10 '17 at 10:01
  • Possible duplicate of [Print content of JavaScript object?](https://stackoverflow.com/questions/1625208/print-content-of-javascript-object) – Suraj Rao Dec 10 '17 at 10:01

1 Answers1

0

You can store the location object into stringify format as a value of radio button.

var inputs = this.props.locations.map((location, i) => {
      let strLoc = JSON.stringify(location); // stringify it
      return (
        <div key={i}>
          <input type="radio" id={i} name="location" value={strLoc} />
          <label htmlFor={'choice' + { i }}>{location.name}</label>
        </div>
      );
    });

In handleSubmit can get back in json/object format.

handleSubmit(e) {
    e.preventDefault();
    let strLoc = JSON.parse(this.state.selectedValue); //parse it back to json/object
    console.log(strLoc.name);
  }

Working codesandbox demo

RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53