How to clear uncontrolled field in react

Viewed 10197

I used to use ref for forms but now I always state for forms, I'm facing an issue where I have to clear a field after user submitted something.

handleSumbit = (e) => {
        e.preventDefault()
        const todoText = this.state.todoText
        if(todoText.length > 0){
            this.refs.todoTextElem = "" // wont work
            this.props.onAddTodo(todoText)
        } else {
            this.refs.todoTextElem.focus() //worked
        }
    }

    render() {
        return(
            <div>
                <form onSubmit={this.handleSumbit}>
                    <input ref="todoTextElem" type="text" onChange={e => this.setState({todoText: e.target.value})} name="todoText" placeholder="What do you need to do?" />
                    <button className="button expanded">Add Todo</button>
                </form>
            </div>
        )
    }

Clearing the ref simply don't work because it's a controlled input. I don't want to do something stupid like

passing a flag from parent component telling the form is submitted then use setState to clear the input. Or make onAddTodo to have a callback so that I can do

this.props.onAddTodo(todoText).then(()=>this.state({todoText:""}))
2 Answers
Related