Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get refs from another component in React JS

Tags:

The code in main App component is as follows :

class App extends Component {
  componentDidMount(){
      console.log(this.ref);
      debugger;
  }

  render() {

    return (
        <div>
            <Header/>
            {this.props.children}
            <Footer/>
        </div>
    );
  }
}

And one of the components which renders with {this.props.children} is HomePage, where are sections with refs.

The code of a HomePage is as follows :

render(){
     return (
        <div className="homeMain">
            <section ref="info"> <Info/> </section>

            <section ref="contact"> <Contact /> </section>
       </div>
    );
}

How can I get those refs inside App component to be able to pass them as props to header?

I'm trying to do it inside componentDidMount in App component, but console.log(this.refs) is empty.

Any advice?

EDIT

The whole App component :

import React, {Component} from 'react';
import Footer from './common/footer';
import Header from './common/header';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as actions from './components/homepage/login/authActions';

class App extends Component {
    componentDidMount(){
        console.log(this.props.children.refs);
        debugger;

    }

    render() {
        return (
            <div>
                <Header route={this.props.location.pathname}
                        language={this.props.language.labels}
                        authenticated={this.props.authenticated}
                        signoutAction={this.props.actions}
                        offsets={this.props.offsets}
                />
                {React.cloneElement(this.props.children, {
                    currentLanguage: this.props.language.labels,
                    authenticated: this.props.authenticated
                })}
                <div className="clearfix"/>
                <Footer currentLanguage={this.props.language.labels}/>
            </div>
        );
    }
}

function mapStateToProps(state, ownProps) {
    return {
        language: state.language,
        authenticated: state.auth.authenticated,
        offsets: state.offsets
    };
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(actions, dispatch)
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(App);
like image 227
Boky Avatar asked Oct 17 '16 07:10

Boky


People also ask

How do you pass ref to another component React?

We define a ref in the component that needs the ref and pass it to the button component. React will pass the ref through and forward it down to <input ref={ref}> by specifying it as a JSX attribute. When the ref is attached, ref. current will point to the <input> DOM node.

Can we use ref on React component?

In react, there is another way to use refs that is called "callback refs" and it gives more control when the refs are set and unset. Instead of creating refs by createRef() method, React allows a way to create refs by passing a callback function to the ref attribute of a component. It looks like the below code.


1 Answers

The React's main idea is passing props downward from parent to children (even to deeper levels of children - grandchildren I mean)

Therefore, when we want the parent to do something which is triggered from (or belongs to) the children, we can create a callback function in the parent, then pass it down to children as props

For your preference, this is a demonstration on how to pass callback functions downward through many levels of children and how to trigger them:

Force React container to refresh data

Re-initializing class on redirect

In your case, you can access refs from children components as follows: (using string for ref - as you stated)

Parent Component:

import React, { Component } from 'react';
// import Child component here

export default class Parent extends Component {
  constructor(props){
    super(props);
    // ...
    this.getRefsFromChild = this.getRefsFromChild.bind(this);
  }    

  getRefsFromChild(childRefs) {
    // you can get your requested value here, you can either use state/props/ or whatever you like based on your need case by case
    this.setState({
      myRequestedRefs: childRefs
    });
    console.log(this.state.myRequestedRefs); // this should have *info*, *contact* as keys
  }    

  render() {
    return (
      <Child passRefUpward={this.getRefsFromChild} />
    )
  }  
}

Child Component:

import React, { Component } from 'react';

export default class Child extends Component {
  constructor(props){
    super(props);
    // ...
  }    

  componentDidMount() {
    // pass the requested ref here
    this.props.passRefUpward(this.refs);

  }    

  render() {
    return (
      <div className="homeMain">
        <section ref="info"> <Info/> </section>

        <section ref="contact"> <Contact /> </section>
      </div>          
    )
  }  
}  
like image 68
thinhvo0108 Avatar answered Sep 27 '22 19:09

thinhvo0108