[EDIT] HAS BEEN FIXED (scroll to bottom)
Hi I am trying to select a react element for a functional component, current code:
const Emoji = (props) => {
const copyButton = useRef(null);
function handleHover(e) {
console.log(this.copyButton); //want to select this element
}
function handleMouseOut(e) {
}
return(
<div className="wrapper">
<div id={"emoji-"+props.id} className="emoji" onMouseOver={handleHover} onMouseOut={handleMouseOut}>
<Button ref={copyButton} className="copyButton" buttonText="Copy" buttonColour="primary" />
<Button className="button" buttonText="Information" buttonColour=" " />
<h1>{props.emojiCharacter}</h1>
<p>{props.emojiName}</p>
</div>
</div>
);
}
export default Emoji;
I am trying to build an app where when the user hovers over this component the buttons will appear, but when I try to select them I keep getting this error: TypeError: Cannot read property 'copyButton' of undefined
It also returns null when I try to document.getElementById as well.
Any suggestions? Thanks.
FIXED
The problem was due to the element being a custom component and not a default component, otherwise I could've simply just used copyButton.current
I fixed it by going into the component's jsx and changing the const Button = (props) => { etc } declaration to a
const Button = React.forwardRef((props, ref) => (
<div ref={ref}
</div>
));
This article did it https://reactjs.org/docs/forwarding-refs.html