Matt K
Matt K

Reputation: 34

Cannot access props in method reactjs

I have a child component that is meant to close when the user clicks outside of the function. I am able to detect the click outside using the onclickoustide library, but the issue is that I don't want the state of the component to be changed if the component has already disappeared. That is why I checked to see what the css display was. This can all be seen in the handleClickOutside method. Instead of changing the display, I did console.log to see if it is working. My code looks like this:

import React, { useState, useEffect } from 'react';
import onClickOutside from 'react-onclickoutside';

function TaskOptions({ display, changeState }) {
    const [styleDisplay, setDisplay] = useState(display);

    useEffect(() => {
        setDisplay(display);
    }, [display])

    TaskOptions.handleClickOutside = () => {
        if(display === "initial") {
            console.log('hi')
        }

        console.log(display)
    }


    

    return (
        <div 
            className="card"
            style={{
                display: styleDisplay
            }}
        >
            <div className="btn-group">
                <button className="btn btn-light" onClick={() => console.log(display)}>Edit</button>
                <button className="btn btn-light">Duplicate</button>
                <button className="btn btn-light">Delete</button>
            </div>
        </div>
    );
}

const clickOutsideConfig = {
    handleClickOutside: () => TaskOptions.handleClickOutside
};

export default onClickOutside(TaskOptions, clickOutsideConfig);

What should happen is the console should print 'hi' when I click outside of the element. However, it only outputs the value of the display prop. This display prop is undefined. However if you go to the edit button, it outputs display too when you click it, however the values are completely different. The click outside outputs undefined, while the button outputs the true display value.

Upvotes: 0

Views: 173

Answers (1)

Andreas &#197;gren
Andreas &#197;gren

Reputation: 3929

The TaskOptions.handleClickOutside function needs to form a closure around the display argument, then you'll capture the value correctly:

TaskOptions.handleClickOutside = () => {
    if(display === "initial") {
        console.log('hi')
    }

    console.log(display) // Changed from TaskOptions.display
}

Here's a working example: https://codesandbox.io/s/trusting-turing-vplp2?file=/src/App.js

enter image description here

Upvotes: 1

Related Questions