Search code examples
javascriptreactjsradio-button

How to pass multiple values in react through radio input


I want to pass the value of the whole row of a table to a function when the radio button in the row is selected. This is the table code

<table className="table table-bordered table-stripped">
                <thead>
                    <th>AD Type</th>
                    <th>AD Title</th>
                    <th>Image/Video URL</th>
                    <th>Video Thumbnail</th>
                    <th>Landing URL</th>
                    <th>Placement</th>
                    <th>Country</th>
                    <th>DSP</th>
                    <th>Select</th>
                </thead>
                <tbody>
                    {
                        creative.map(
                            creative =>
                            <tr key = {creative.id}>
                                <td>{creative.ad_type}</td>
                                <td>{creative.ad_title}</td>
                                <td>{creative.image_url}</td>
                                <td>{creative.video_thumbnail}</td>
                                <td>{creative.landing_url}</td>
                                <td>{creative.placement}</td>
                                <td>{creative.country}</td>
                                <td>{creative.dsp}</td> 
                                <td> <input type="radio" class="checkbox1" id="chk" name="check[]" value={creative} onClick={func1} /></td>
                            </tr>
                        )
                    }
                </tbody>
            </table>

And the function func1 simply logs the value

const func1 = (e) => {
    console.log(e.target.value);
}

When I'm using value = {creative}, the logged output is [object Object]. I even tried using value = {creative.ad_type, creative.ad_title} but then it only logs the last value, in this case, creative.ad_title. I want to log all the values of the creative object.


Solution

  • You can use JSON.stringify() to turn the object value to JSON format.

    ex:

    value{ JSON.stringify(creative) }
    

    And then you try to get the value you need to parse it with JSON.parse()

    const func1 = (e) => {
      console.log(JSON.parse(e.target.value);
    }