React - use ref in component AND pass it to parent in props












2















Update: my problem was actually due to typos – the general approach works fine if you'd like to use a child element ref in both a child and parent component.



Here's a working example of the approach that works:
https://codesandbox.io/s/rwj7z7o7oo





Original post:



I'm trying to forward a ref to the parent component, while also making the ref accessible for functions in the child (which is a class). Currently, I can successfully pass the ref to the parent, but the ref is no longer accessible in the child.



class Child extends React.Component {
// Unable to access the forwarded ref here:
componentDidMount() {
console.log(this.props.forwardedRef); // null
}

render() {
return <input type="text" ref={this.props.forwardedRef} />
}
}

// Parent is able to access the ref:
const Parent = () => {
const childRef = useRef(null);

function handleClick() {
console.log(childRef.current); // correctly ref's the input el
}

return (
<Child forwardedRef={childRef} onClick={handleClick} />
);
}


Is there another approach will let me use the ref in both Child and Parent?










share|improve this question

























  • You wish to pass the child's ref up to the parent but your current code is not working, correct?

    – Shawn Andrews
    Nov 22 '18 at 5:19











  • Hi Shawn - yes, in the example code, the child's ref is successfully passed up to the parent, but the ref is not accessible in the child itself.

    – Stephen
    Nov 22 '18 at 5:20
















2















Update: my problem was actually due to typos – the general approach works fine if you'd like to use a child element ref in both a child and parent component.



Here's a working example of the approach that works:
https://codesandbox.io/s/rwj7z7o7oo





Original post:



I'm trying to forward a ref to the parent component, while also making the ref accessible for functions in the child (which is a class). Currently, I can successfully pass the ref to the parent, but the ref is no longer accessible in the child.



class Child extends React.Component {
// Unable to access the forwarded ref here:
componentDidMount() {
console.log(this.props.forwardedRef); // null
}

render() {
return <input type="text" ref={this.props.forwardedRef} />
}
}

// Parent is able to access the ref:
const Parent = () => {
const childRef = useRef(null);

function handleClick() {
console.log(childRef.current); // correctly ref's the input el
}

return (
<Child forwardedRef={childRef} onClick={handleClick} />
);
}


Is there another approach will let me use the ref in both Child and Parent?










share|improve this question

























  • You wish to pass the child's ref up to the parent but your current code is not working, correct?

    – Shawn Andrews
    Nov 22 '18 at 5:19











  • Hi Shawn - yes, in the example code, the child's ref is successfully passed up to the parent, but the ref is not accessible in the child itself.

    – Stephen
    Nov 22 '18 at 5:20














2












2








2


1






Update: my problem was actually due to typos – the general approach works fine if you'd like to use a child element ref in both a child and parent component.



Here's a working example of the approach that works:
https://codesandbox.io/s/rwj7z7o7oo





Original post:



I'm trying to forward a ref to the parent component, while also making the ref accessible for functions in the child (which is a class). Currently, I can successfully pass the ref to the parent, but the ref is no longer accessible in the child.



class Child extends React.Component {
// Unable to access the forwarded ref here:
componentDidMount() {
console.log(this.props.forwardedRef); // null
}

render() {
return <input type="text" ref={this.props.forwardedRef} />
}
}

// Parent is able to access the ref:
const Parent = () => {
const childRef = useRef(null);

function handleClick() {
console.log(childRef.current); // correctly ref's the input el
}

return (
<Child forwardedRef={childRef} onClick={handleClick} />
);
}


Is there another approach will let me use the ref in both Child and Parent?










share|improve this question
















Update: my problem was actually due to typos – the general approach works fine if you'd like to use a child element ref in both a child and parent component.



Here's a working example of the approach that works:
https://codesandbox.io/s/rwj7z7o7oo





Original post:



I'm trying to forward a ref to the parent component, while also making the ref accessible for functions in the child (which is a class). Currently, I can successfully pass the ref to the parent, but the ref is no longer accessible in the child.



class Child extends React.Component {
// Unable to access the forwarded ref here:
componentDidMount() {
console.log(this.props.forwardedRef); // null
}

render() {
return <input type="text" ref={this.props.forwardedRef} />
}
}

// Parent is able to access the ref:
const Parent = () => {
const childRef = useRef(null);

function handleClick() {
console.log(childRef.current); // correctly ref's the input el
}

return (
<Child forwardedRef={childRef} onClick={handleClick} />
);
}


Is there another approach will let me use the ref in both Child and Parent?







reactjs react-hooks






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 '18 at 5:46







Stephen

















asked Nov 22 '18 at 5:03









StephenStephen

332120




332120













  • You wish to pass the child's ref up to the parent but your current code is not working, correct?

    – Shawn Andrews
    Nov 22 '18 at 5:19











  • Hi Shawn - yes, in the example code, the child's ref is successfully passed up to the parent, but the ref is not accessible in the child itself.

    – Stephen
    Nov 22 '18 at 5:20



















  • You wish to pass the child's ref up to the parent but your current code is not working, correct?

    – Shawn Andrews
    Nov 22 '18 at 5:19











  • Hi Shawn - yes, in the example code, the child's ref is successfully passed up to the parent, but the ref is not accessible in the child itself.

    – Stephen
    Nov 22 '18 at 5:20

















You wish to pass the child's ref up to the parent but your current code is not working, correct?

– Shawn Andrews
Nov 22 '18 at 5:19





You wish to pass the child's ref up to the parent but your current code is not working, correct?

– Shawn Andrews
Nov 22 '18 at 5:19













Hi Shawn - yes, in the example code, the child's ref is successfully passed up to the parent, but the ref is not accessible in the child itself.

– Stephen
Nov 22 '18 at 5:20





Hi Shawn - yes, in the example code, the child's ref is successfully passed up to the parent, but the ref is not accessible in the child itself.

– Stephen
Nov 22 '18 at 5:20












1 Answer
1






active

oldest

votes


















2














useRef returns values that are like instance variables classes. In your case, there is nothing that would cause the component to render even if your set the ref and hence componentDidUpdate of child wouldn't run.



Also you haven't returned anything from Child component.



class Child extends React.Component {
// Unable to access the forwarded ref here:
componentDidUpdate(prevProps) {
console.log(this.props.forwardedRef); // null
console.log(prevProps.forwardedRef); // null
}

render() {
return (
<React.Fragment>
<input type="text" ref={this.props.forwardedRef} />
<div>{this.props.count}</div>
<input type="button" onClick={this.props.onClick} value={"Click"} />
</React.Fragment>
);
}
}

// Parent is able to access the ref:
const Parent = () => {
const childRef = useRef(null);
const [count, setCount] = useState(0);

function handleClick() {
console.log(childRef.current); // correctly ref's the input el
setCount(count => count + 1);
}

return <Child forwardedRef={childRef} count={count} onClick={handleClick} />;
};


Working demo






share|improve this answer
























  • Thanks Shubham – I don't use class components much and made a mistake. You can substitute componentDidMount (I edited my original question). I also added 'return' to the Child's render function, thanks for pointing out the typo. The main issue I'm trying to solve is that the ref isn't available for use in any child functions.

    – Stephen
    Nov 22 '18 at 5:37













  • Ah thanks Shubham - your correction of my typos helped me figure it out. I forgot that componentDidUpdate doesn't run on the initial render of the component.

    – Stephen
    Nov 22 '18 at 5:41











  • @Stephen, Even componentDidMount is called on initial render and since the ref of the parent will update but no re-render is called to update props it isn't reflecting in componentDidMount.

    – Shubham Khatri
    Nov 22 '18 at 5:41












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53424183%2freact-use-ref-in-component-and-pass-it-to-parent-in-props%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














useRef returns values that are like instance variables classes. In your case, there is nothing that would cause the component to render even if your set the ref and hence componentDidUpdate of child wouldn't run.



Also you haven't returned anything from Child component.



class Child extends React.Component {
// Unable to access the forwarded ref here:
componentDidUpdate(prevProps) {
console.log(this.props.forwardedRef); // null
console.log(prevProps.forwardedRef); // null
}

render() {
return (
<React.Fragment>
<input type="text" ref={this.props.forwardedRef} />
<div>{this.props.count}</div>
<input type="button" onClick={this.props.onClick} value={"Click"} />
</React.Fragment>
);
}
}

// Parent is able to access the ref:
const Parent = () => {
const childRef = useRef(null);
const [count, setCount] = useState(0);

function handleClick() {
console.log(childRef.current); // correctly ref's the input el
setCount(count => count + 1);
}

return <Child forwardedRef={childRef} count={count} onClick={handleClick} />;
};


Working demo






share|improve this answer
























  • Thanks Shubham – I don't use class components much and made a mistake. You can substitute componentDidMount (I edited my original question). I also added 'return' to the Child's render function, thanks for pointing out the typo. The main issue I'm trying to solve is that the ref isn't available for use in any child functions.

    – Stephen
    Nov 22 '18 at 5:37













  • Ah thanks Shubham - your correction of my typos helped me figure it out. I forgot that componentDidUpdate doesn't run on the initial render of the component.

    – Stephen
    Nov 22 '18 at 5:41











  • @Stephen, Even componentDidMount is called on initial render and since the ref of the parent will update but no re-render is called to update props it isn't reflecting in componentDidMount.

    – Shubham Khatri
    Nov 22 '18 at 5:41
















2














useRef returns values that are like instance variables classes. In your case, there is nothing that would cause the component to render even if your set the ref and hence componentDidUpdate of child wouldn't run.



Also you haven't returned anything from Child component.



class Child extends React.Component {
// Unable to access the forwarded ref here:
componentDidUpdate(prevProps) {
console.log(this.props.forwardedRef); // null
console.log(prevProps.forwardedRef); // null
}

render() {
return (
<React.Fragment>
<input type="text" ref={this.props.forwardedRef} />
<div>{this.props.count}</div>
<input type="button" onClick={this.props.onClick} value={"Click"} />
</React.Fragment>
);
}
}

// Parent is able to access the ref:
const Parent = () => {
const childRef = useRef(null);
const [count, setCount] = useState(0);

function handleClick() {
console.log(childRef.current); // correctly ref's the input el
setCount(count => count + 1);
}

return <Child forwardedRef={childRef} count={count} onClick={handleClick} />;
};


Working demo






share|improve this answer
























  • Thanks Shubham – I don't use class components much and made a mistake. You can substitute componentDidMount (I edited my original question). I also added 'return' to the Child's render function, thanks for pointing out the typo. The main issue I'm trying to solve is that the ref isn't available for use in any child functions.

    – Stephen
    Nov 22 '18 at 5:37













  • Ah thanks Shubham - your correction of my typos helped me figure it out. I forgot that componentDidUpdate doesn't run on the initial render of the component.

    – Stephen
    Nov 22 '18 at 5:41











  • @Stephen, Even componentDidMount is called on initial render and since the ref of the parent will update but no re-render is called to update props it isn't reflecting in componentDidMount.

    – Shubham Khatri
    Nov 22 '18 at 5:41














2












2








2







useRef returns values that are like instance variables classes. In your case, there is nothing that would cause the component to render even if your set the ref and hence componentDidUpdate of child wouldn't run.



Also you haven't returned anything from Child component.



class Child extends React.Component {
// Unable to access the forwarded ref here:
componentDidUpdate(prevProps) {
console.log(this.props.forwardedRef); // null
console.log(prevProps.forwardedRef); // null
}

render() {
return (
<React.Fragment>
<input type="text" ref={this.props.forwardedRef} />
<div>{this.props.count}</div>
<input type="button" onClick={this.props.onClick} value={"Click"} />
</React.Fragment>
);
}
}

// Parent is able to access the ref:
const Parent = () => {
const childRef = useRef(null);
const [count, setCount] = useState(0);

function handleClick() {
console.log(childRef.current); // correctly ref's the input el
setCount(count => count + 1);
}

return <Child forwardedRef={childRef} count={count} onClick={handleClick} />;
};


Working demo






share|improve this answer













useRef returns values that are like instance variables classes. In your case, there is nothing that would cause the component to render even if your set the ref and hence componentDidUpdate of child wouldn't run.



Also you haven't returned anything from Child component.



class Child extends React.Component {
// Unable to access the forwarded ref here:
componentDidUpdate(prevProps) {
console.log(this.props.forwardedRef); // null
console.log(prevProps.forwardedRef); // null
}

render() {
return (
<React.Fragment>
<input type="text" ref={this.props.forwardedRef} />
<div>{this.props.count}</div>
<input type="button" onClick={this.props.onClick} value={"Click"} />
</React.Fragment>
);
}
}

// Parent is able to access the ref:
const Parent = () => {
const childRef = useRef(null);
const [count, setCount] = useState(0);

function handleClick() {
console.log(childRef.current); // correctly ref's the input el
setCount(count => count + 1);
}

return <Child forwardedRef={childRef} count={count} onClick={handleClick} />;
};


Working demo







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 22 '18 at 5:28









Shubham KhatriShubham Khatri

94.7k15119160




94.7k15119160













  • Thanks Shubham – I don't use class components much and made a mistake. You can substitute componentDidMount (I edited my original question). I also added 'return' to the Child's render function, thanks for pointing out the typo. The main issue I'm trying to solve is that the ref isn't available for use in any child functions.

    – Stephen
    Nov 22 '18 at 5:37













  • Ah thanks Shubham - your correction of my typos helped me figure it out. I forgot that componentDidUpdate doesn't run on the initial render of the component.

    – Stephen
    Nov 22 '18 at 5:41











  • @Stephen, Even componentDidMount is called on initial render and since the ref of the parent will update but no re-render is called to update props it isn't reflecting in componentDidMount.

    – Shubham Khatri
    Nov 22 '18 at 5:41



















  • Thanks Shubham – I don't use class components much and made a mistake. You can substitute componentDidMount (I edited my original question). I also added 'return' to the Child's render function, thanks for pointing out the typo. The main issue I'm trying to solve is that the ref isn't available for use in any child functions.

    – Stephen
    Nov 22 '18 at 5:37













  • Ah thanks Shubham - your correction of my typos helped me figure it out. I forgot that componentDidUpdate doesn't run on the initial render of the component.

    – Stephen
    Nov 22 '18 at 5:41











  • @Stephen, Even componentDidMount is called on initial render and since the ref of the parent will update but no re-render is called to update props it isn't reflecting in componentDidMount.

    – Shubham Khatri
    Nov 22 '18 at 5:41

















Thanks Shubham – I don't use class components much and made a mistake. You can substitute componentDidMount (I edited my original question). I also added 'return' to the Child's render function, thanks for pointing out the typo. The main issue I'm trying to solve is that the ref isn't available for use in any child functions.

– Stephen
Nov 22 '18 at 5:37







Thanks Shubham – I don't use class components much and made a mistake. You can substitute componentDidMount (I edited my original question). I also added 'return' to the Child's render function, thanks for pointing out the typo. The main issue I'm trying to solve is that the ref isn't available for use in any child functions.

– Stephen
Nov 22 '18 at 5:37















Ah thanks Shubham - your correction of my typos helped me figure it out. I forgot that componentDidUpdate doesn't run on the initial render of the component.

– Stephen
Nov 22 '18 at 5:41





Ah thanks Shubham - your correction of my typos helped me figure it out. I forgot that componentDidUpdate doesn't run on the initial render of the component.

– Stephen
Nov 22 '18 at 5:41













@Stephen, Even componentDidMount is called on initial render and since the ref of the parent will update but no re-render is called to update props it isn't reflecting in componentDidMount.

– Shubham Khatri
Nov 22 '18 at 5:41





@Stephen, Even componentDidMount is called on initial render and since the ref of the parent will update but no re-render is called to update props it isn't reflecting in componentDidMount.

– Shubham Khatri
Nov 22 '18 at 5:41




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53424183%2freact-use-ref-in-component-and-pass-it-to-parent-in-props%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

mysqli_query(): Empty query in /home/lucindabrummitt/public_html/blog/wp-includes/wp-db.php on line 1924

How to change which sound is reproduced for terminal bell?

Can I use Tabulator js library in my java Spring + Thymeleaf project?