0

According to React spec: https://reactjs.org/docs/refs-and-the-dom.html "There are a few good use cases for refs: Managing focus, text selection, or media playback. Triggering imperative animations. Integrating with third-party DOM libraries. Avoid using refs for anything that can be done declaratively."

That's why I'm not so sure for now, whether I used ref properly or not in this case:

export let FormInput = createReactClass({
    handleInput(e){
        e.preventDefault();
        const product = this.name.value;
        const red = this.red.checked;
        this.props.addProduct(product,red);
        this.inputForm.reset();
    },
    render(){
        return(
            <form className="prod_input" ref={x => this.inputForm = x} onSubmit={this.handleInput}>
                <input type="text" ref={x => this.name = x} placeholder="Product name"/>
                <input type="checkbox" ref={x => this.red = x} value="true"/>
                <input type="submit" hidden/>
            </form>
            )
    }
})

If not, how could it be rearranged in order to replace ref to onChange={}?

Seemax
  • 121
  • 12
  • 2
    your input elements are currently uncontrolled, you can get rid of ref by making them controlled. check this https://stackoverflow.com/questions/44471370/reactjs-should-you-have-controlled-or-uncontrolled-inputs/44471458#44471458 – Shubham Khatri Oct 31 '17 at 10:53

1 Answers1

0

You can avoid using refs by making your input fields controlled. Here is an example:

export let FormInput = createReactClass({

    constructor(props){
        super(props);
        this.state = {
            name: '',
        };
    }

    handleNameChange(updatedName){
        this.setState({ name: updatedName });
    }

    handleInput(e){
        e.preventDefault();
        const product = this.state.name;
        // ...
        this.props.addProduct(product);
        this.inputForm.reset();
    },

    render(){
        return (
            <form className="prod_input" ref={x => this.inputForm = x} onSubmit={this.handleInput}>
                <input type="text" value={this.state.name} placeholder="Product name" onChange={e => this.handleNameChange(e.target.value)} />
               // ...
            </form>
        );
    }
})   

The idea is to keep the value of your fields in your local state. Then you can set the value of each of your fields to the value currently stored in your state, and attach an onChange handler that updates this value every the user types something. When you submit your form, all your values are available directly in your component's state.