Search code examples
reactjsrefstyled-componentsreact-props

Accessing The Ref of a Component Passed Down as Props?


I am passing down a styled component

const Text = styled.span`
   font-size: 10px
`

render(){
   <Test comp = {<Text innerRef={(ref)=>{this.ref=ref}}>Hello</Text>}/>
}

Inside of the Test component I want to access the ref of Text but I am having trouble doing so. Is this possible? I want to get access to the font-size value inside of Test. Thanks in advance for all help.


Solution

  • Since you're passing a component as a prop to another component, React does not render it at all, and therefor you have no ref.

    If your goal is to wrap Text in Test, the proper way to do so is passing it as a child. That way React will actually render the component, and will produce its ref.

    const Text = styled.span`
       font-size: 10px
    `
    
    render(){
       <Test>
         <Text innerRef={ref => this.ref = ref}>Hello</Text>
       </Test>
    }
    

    If you want to access the ref in Test, you can do it via this.props.children.ref

    EDIT

    Since styled-components have their own prop for getting the ref, you need to use React.createRef() and access the ref via the props:

    const Text = styled.span`
       font-size: 10px
    `
    
    class Test extends React.PureComponent {
      componentDidMount() {
        // This is how you access the ref ;)
        console.log(this.props.children.props.innerRef.current);
      }
    
      render() {
        return (
          <div className='test'>{this.props.children}</div>
        );
      }
    }
    
    class App extends React.PureComponent {
    
      render() {
        return (
          <Test>
            <Text innerRef={React.createRef()}/>
          </Test>
        );
      }
    }