kushalvm kushalvm - 3 years ago 138
React JSX Question

Access input value in ReactDOM.render

I need to get input field's value inside a click handler inside ReactDOM.render().

The code inside App.js is

<input ref={node => {
this.todoInput = node
}} className="pull-left" />
<button onClick={this.props.addTodo}>Add Todo</button>


addTodo={() => {

// type: 'ADD_TODO',
// id: nextTodoId++,
{/*text: this.refs.todoInput.value*/}

{/*this.refs.todoInput.value = '';*/}

Inside addTodo function , how can I access my refs object? Or ultimately to get todoInput's value

Update - One of the answers provided below works for me as an alternative solution. However, the reason what is bugging me is simple. I render App component inside of the ReactDOM.render(). Shouldn't App directly have access to it's input field as it is through some mechanism ?

Answer Source

In your code, you refer the todo inside addTodo function like this.refs.todoInput. Here this refers to the current instance where you are rendering ReactDOM.render. So your input which is inside the app instance cannot be accessed in a different instance.

If you wanna access it your way then you need to add a ref to your app like this

 ref={appInstance => { this.appInstance = appInstance;} }

Now you can access the input inside app instance like below

addTodo={() => {
  // your value from todoInput will be here..
  const value = this.appInstance.todoInput.value;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download