Sunday, 4 June 2017

Dynamic radio button form react

I am building a dynamic form that fetches entry from a db, the row results will render in a form. I have a component to render each entry in the form The component of the form-row

class Juego extends React.Component {
render () {
    return(
        <tr>
            <td>{shortDate(this.props.juego.fecha)}</td>
            <td>
                <input type="radio" name={`apuesta[${this.props.juego.id}]`}  value="G" id={this.props.juego.id} onChange={this.props.handleChange} />
                <label>{this.props.juego.local}</label>
                <span className="pull-right">{this.props.juego.spread_eq_local}</span>
            </td>

            <td>
                <input type="radio" name={`apuesta[${this.props.juego.id}]`} value="E" id={this.props.juego.id} onChange={this.props.handleChange} />
                <label>Empate</label>
                <span className="pull-right">{this.props.juego.spread_empate}</span>
            </td>

            <td>
                <input type="radio" name={`apuesta[${this.props.juego.id}]`} value="P" id={this.props.juego.id} onChange={this.props.handleChange} />
                <label>{this.props.juego.visitante}</label>
                <span className="pull-right">{this.props.juego.spread_eq_visitante}</span>
            </td>
            <td>
                <input type="number" name={`puntos[${this.props.juego.id}]`} id={this.props.juego.id} onChange={this.props.handleChange} />
            </td>
        </tr>
    )
}

}

The rows are mapped this way

juegosList=()=>{
    return (
        <div className="lista-juegos">

            <table className="table table-striped">
                <tbody>
                    {this.props.juegos.map(jueg=><Juego juego={jueg}  key={jueg.id} handleChange={this.handleAddBet} addToState={this.addState}/>)}
                </tbody>
            </table>
        </div>
    )
}

And finally rendered on the main component

render () {
    return (
        <div className="juegos-form">
            <form onSubmit={this.handleSubmit}>
                {this.props.juegos.length===0?this.empty:this.juegosList()}
                <button className="btn btn-lg btn-success pull-right">Apostar</button>
            </form>
        </div>

    )
}

I am trying to achieve this passing the values of the Juego component into the state of the main component as an array

apuestas:[
            {id,
            apuesta,
            puntos},
            {id,
            apuesta,
            puntos}
        ]

Something like this, but I am having trouble passing these values into the state of the main component.

Does anyone can think of how to make this work or a better approach?

I am using NodeJS, React, Redux, Express and MySQL

Thanks in advance,



via Héctor Monárrez

No comments:

Post a Comment