Skip to content Skip to sidebar Skip to footer

React: Send Ref Back To Container Component?

I have a presentation component, which takes in a function from its container component as a prop. I want to return a ref as an argument with the function back to the container com

Solution 1:

Imho best practice would be to pass an onchange handler from as prop to your EmailInputView like:

classEmailInputContainerextendsComponent {

   handleChange: function(event) {
      this.setState({myEmail: event.target.value});
   }

   render(){
      return(
         <EmailInputViewonChange={this.handleChange.bind(this)} />
      )
   }
}

and:

<inputonChange={this.props.onChange}style={Styles.emailInputForm.emailInput}type="text" />

in the EmailInputView itself. Works with

<formonSubmit={this.props.onChange}>
  ...
</form>

too (havent checked the event u might have to adjust the handler in the EmailInputContainer slightly).

In this case u dont have to pass a ref which fits much better with the philisophy of react. Imho you should never ever pass a ref the way u wanted to and only use refs in the component you are in when there is no other way.

Optinal (if u dont want to submit the form):

classEmailInputextendsComponent {

  onChange(event) {
     this.setState({myEmail: event.target.value});
  }

  onSubmit() {
     this.props.onChange(this.state.myEmail); //u should rename the prop i just named it so it fits with the example of the parent component above
  }

  render() {
     return (
        <Cell><inputonChange={this.onChange} /><buttononClick={this.onSubmit} /></Cell>
     );
  }

}

there is no need to use a form at all if you dont want to prevent its functionalitly afterwards. If u still want to post the data without page reload u have to implement an Ajax call anyways.

Solution 2:

In your presentation component, capture the ref node through a callback function when it renders, then pass the node value back to your parent on submit.

let inputNode

const EmailInputView = (functions) => (
  <Gridstyle={Styles.emailInputView.container}verticalAlign='middle'>

    ...  

    <Cellwidth='5/12'align='right'><formonSubmit={() => functions.addEmailToList(inputNode.value)} <-- update here
      >
        <inputstyle={Styles.emailInputForm.emailInput}ref={node => inputNode = node} <-- this is what you want

          type="text" name="email" placeholder="Your email address" />
        <inputstyle={Styles.emailInputForm.submitButton}type="submit"value="Submit" /></form></Cell></Grid>
)

Then update your handler:

addEmailToList(value){
  console.log(value)
}

So this solution is great especially when you don't have a parent that's handling anything, such as dispatching a redux action directly from the component that has the input field. However @Aligertor's answer is spot on.

Post a Comment for "React: Send Ref Back To Container Component?"