mercredi 21 octobre 2015

React checkbox boolean value in ajax put request / Rails

This is my first foray into React.

I'm working on a checkbox component that I want to use twice. This is the parent component:

    var SearchItem = React.createClass({
        getInitialState: function(){
            return { data: [] };
        },
        render: function(){
            return <div className='searchItem'>
                        <p>{this.props.data.date}</p>
                        <a href={this.props.data.url} target='_blank' {this.props.data.title}</a>
                        <p>{this.props.data.company}</p>
                        <p>{this.props.data.description}</p>    
                        <form>
                            <CheckBox value = {this.props.data.saved} id = {this.props.data.id} text = 'Save' />
                            <CheckBox value = {this.props.data.applied} id = {this.props.data.id} text = 'Applied' />
                        </form>
                    </div>
        }
    });

What I want to do here is make an ajax put request, passing a boolean value for Saved or Applied, depending on the context. This is the checkbox component:

    var CheckBox = React.createClass({
        getInitialState: function(){
            return { data: [] }
        },
        handleClick: function(e){
        $.ajax({
                data: // not sure what to do here,
                dataType: 'json',
                url: '/searches/' + this.props.id + '.json',
                type: 'put',
                context: this,
                success: function(data, status, xhr){
                this.setState({
                    //  not sure what to do here
                });
                }.bind(this),
                error: function(xhr, status, err){  
                    console.log("whoops, something didn't work:"),
                    console.log(status, err.toString());
                }.bind(this)
            });
        },
        render: function(){
            var value = this.props.value;
            return (
                <label><input type='checkbox' className='checkBox' defaultChecked={value} onClick={this.handleClick} />{this.props.text}</label>
            )
        }
    }); 

I want the data value to look like this: { saved: boolean } or { applied: boolean } depending on the whether this is the Saved checkbox or the Applied checkbox.

Problems:

1) Not sure how to set the data value dynamically, so I can reuse this component.

2) This checkbox boolean trick '$('input:checkbox').is('checked') ? true : false' doesn't work because '$('input:checkbox')' returns every checkbox on the page.

3) I suppose data in the success callback should my updated model, and I'll need to grab whatever attribute I just updated in order to set the component's state. Right? But again, I'll need to determine which checkbox it is.




Aucun commentaire:

Enregistrer un commentaire