Search code examples
javascriptreactjsfunctional-programmingstateless

Cannot perform prop function onClick when usnig stateless functions


I can't seem to get my modal button to run the function I have passed into it.

Am I missing something?

Dashboard.js

const Dashboard = () => {

    let show = false;

    const showModal = () => {
        console.log('showing modal');
    };

    const hideModal = () => {
        console.log('closing modal');
    };

    return (
        <div>
            <h1>This is the dashboard</h1>
            <button type="button" onClick={showModal}>Open</button>
            <Modal handleClose={hideModal} show={show}/>
        </div>
    )
};

export default Dashboard;

Modal.js

const Modal = (handleClose, show, children) => {
    const showHideClass = show ? 'show-modal' : 'hide-modal';

    return (
        <div className={showHideClass}>
            <h1>This is my modal!</h1>
            <p>{children}</p>
            <button onClick={handleClose}>Close</button>
        </div>
    );
};

export default Modal;

I had the warning: Expected 'onClick' listener to be a function, instead got a value of 'object' type., so I changed the onClick in modal.js to () => handleClose which dismissed the warning, however nothing happened when I clicked the button...


Solution

  • The Solution

    The issue you're having is you're not destructuring the props object that's passed in.

    const Modal = (handleClose, show, children) => {
    

    should instead put curly braces around the arguments

    const Modal = ({handleClose, show, children}) => {
    

    Brief Explanation

    The props passed to a functional component are a single object with keys that correspond to the name of the object passed in. The object's shape would be:

    {
       handleClose: [function],
       show: true,
       children: ...
    }
    

    To get the props, you can either have a single argument (idiomatically named props), and then access values from that object:

    const Hello = (props) => {
       console.log(props.message);
    }
    

    Or you can use a destructuring assignment (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) to extract the props in the function arguments:

    const Hello = ({message}) => {
       console.log(message);
    }