React - use ref in component AND pass it to parent in props
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
add a comment |
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
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
add a comment |
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
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
reactjs react-hooks
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
add a comment |
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
add a comment |
1 Answer
1
active
oldest
votes
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
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
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
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
add a comment |
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
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
add a comment |
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
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
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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