I have a div element that I want to call a function from when a click event fires on it. The div contains an input field that I don't want to trigger the function, so I'm using useRef
to target only the div element itself and not the contents. I'm creating the reference with the hook, giving the div a ref attribute pointing to that reference, and then passing it an onClick event that first checks if ref.current
is equal to the event target. This method has worked for me in the past when building features such as modals, but for some reason this time the value of ref.current
and the value of the event target are not evaluating as equal, and so the function never fires off. Here's the code:
const VideoEntryTile: React.FC = () => {
const [isExpanded, setIsExpanded] = useState<boolean>(false);
const containerRef = useRef<HTMLDivElement | null>(null)
const handleExpand = (e: any):void => {
console.log(containerRef === e.target) // This evaluates to false
if (containerRef.current === e.target) {
setIsExpanded(true)
}
}
return (
<div
className={styles.VideoEntryTile__Container}
onClick={handleExpand}
ref={containerRef} {/* The reference is set here */}
>
<div className={styles.VideoEntryTile__Top}>
<div className={styles.VideoEntryTile__LeftActions}>
<div className={styles.VideoEntryTile__LeftActions__VideoNameInput}>
<TextField
disabled={false}
inputSize="large"
value="Video 1"
/>
</div>
<div className={styles.VideoEntryTile__LeftActions__GuestsContainer}>
<p>Guests</p>
<input />
</div>
<button type="button">-</button>
<button type="button">+</button>
</div>
<div className={styles.VideoEntryTile__RightActions}>
<p>20</p>
<p>Credits</p>
</div>
</div>
{ isExpanded ?
(
<div className={styles.VideoEntryTile__Bottom}>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
<p>Test</p>
</div>
)
: null }
</div>
);
};
Any idea why this isn't working? This solution has worked for me in the past so I'm not sure why it isn't now.
E: This thread should not have been closed - the provided "answer" has nothing to do with my question.