Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to call child's method or child's refs? #1118

Closed
joonhocho opened this issue Feb 7, 2017 · 8 comments
Closed

How to call child's method or child's refs? #1118

joonhocho opened this issue Feb 7, 2017 · 8 comments

Comments

@joonhocho
Copy link

joonhocho commented Feb 7, 2017

I want to call child method or reference to child's refs.
It should work, but refs.child returns ProxyComponent rather than Child. And, the ProxyComponent does not have method nor refs.root.
I think this is due to having hot module reloading together with withStyles.
Any ideas? I've tried with release mode as well, but to no avail.

Child.js

import React, {PropTypes} from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Child.css';


class Child extends React.Component {
  method() { console.log('child'); }

  render() {
    return (
      <div ref="root">
      </div>
    );
  }
}

export default withStyles(s)(Child);

Parent.js

import React, {PropTypes} from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Parent.css';
import Child from './Child';


class Parent extends React.Component {
  callChildMethod() { this.refs.child.method(); } // doesnt work.

  render() {
    return (
      <div>
        <Child ref="child" />
      </div>
    );
  }
}

export default withStyles(s)(Parent);
@frenzzy
Copy link
Member

frenzzy commented Feb 7, 2017

Like so?

@joonhocho
Copy link
Author

@frenzzy I've tried the suggestion, but it didnt work. It also returned the proxy component.

@frenzzy
Copy link
Member

frenzzy commented Feb 7, 2017

Please explore the demo more carefully: https://jsfiddle.net/frenzzy/z9c46qtv/3/

@joonhocho
Copy link
Author

@frenzzy The demo doesn't really help because I think it's problem caused by hot module reloading.

@frenzzy
Copy link
Member

frenzzy commented Feb 8, 2017

This approach works fine with hot reload in master branch.
Maybe you want to use this and just forgot to bind context?

P.S.: Added a tiny new section to React docs: When to Use Refs

@langpavel
Copy link
Collaborator

@joonhocho Did you resolve it?
I think it is no RSK issue → closing.
Feel free to reopen if you need more help.

@nav123iitr
Copy link

You have to call the function callChildMethod() of your parent component from inside render function.

@chaschev
Copy link

chaschev commented Oct 7, 2018

That's a horrible hack, sorry

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants