0

new react user here.

i am trying to access form data in my parent app from the child form. I am trying to alert or console the data from the parent so I can visually see what was typed in the form. Once I can access the data in the parent I will try and move it to my list array.

PARENT

class App extends Component {

    constructor() {
    super();
    this.state = {
    lists: [], 
    items: {} 
    };
}

handleAddList(s) {
     alert('I am calling function from child')

     console.log(this.refs.id.value) // this errors out on me
}

 render() {
 return (
    <div className="App">
    <AddList addList={this.handleAddList.bind(this)} />
    <div id="listsDiv" className="List">
    <Lists lists={this.state.lists} items={this.state.items} addItem {this.handleAddItem.bind(this)} />
    </div>
    </div>
 );
 }

 }

CHILD

class AddList extends Component {


handleSubmit(e) {
   e.preventDefault(); 
   alert(this.refs.id.value)

   this.props.addList()

}

render() {
  return (
    <div id="addListDiv">
    <form onSubmit={this.handleSubmit.bind(this)}>
    <div id='addList'>
    <label>What will be on your next list?&nbsp;
    <input type='text' ref='id' id='newID'></input>
    </label>
    </div><br />
    <input type='submit' value='Create List' />
    </form>
    </div>
   );
 }
}

2 Answers 2

1

You should set the ref on the input using a callback, like this:

<input type='text' ref={input => { this.input = input; }} id='newID'></input>

Then access it in your event handler like this:

alert(this.input.value);

However, if you are new to React, you should try using controlled components before you try to use refs.

https://reactjs.org/docs/forms.html

Sign up to request clarification or add additional context in comments.

Comments

0

CHILD

import ReactDOM from 'react-dom';
class AddList extends Component {


handleSubmit(e) {
  e.preventDefault();
  var day = ReactDOM.findDOMNode(this.refs.id).value.trim();

  this.props.addList(day);

}

render() {
   return (
     <div id="addListDiv">
     <form onSubmit={this.handleSubmit.bind(this)}>
     <div id='addList'>
     <label>What will be on your next list?&nbsp;
     <input type='text' ref='id' id='newID'></input>
     </label>
     </div><br />
     <input type='submit' value='Create List' />
     </form>
   </div>
    );
  }
}

PARENT

class App extends Component {

handleAddList(args) {
   console.log(args);
}

render() {
   return (
    <div className="App">
      <AddList addList={this.handleAddList.bind(this)} />
   </div>
   );
  }
 }

Edit it a little to work for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.