Search code examples
reactjsstorybook

How to pass a function as a prop to React function component?


Im trying to pass a function down as a prop. Why is this not working?

In Parent:

const dummyProps = {
    label: "Text",
    increment: function() {
        console.log("+");
    },
};

function Parent() {
    return (
        <div>
            <Child {...dummyProps} />
        </div>
    );
}

In Child:

function InputNumeric({ label, increment }) {
    return(
        <label>{label}</label>
        <button onClick={increment}>Click</button>
    )
}

Solution

  • In React, you need to have a single parent element that is rendered. In your question you forgot to wrap the elements inside the child component. You can wrap with another element or with a React.Fragment (shorthand syntax is <> </>)

    function InputNumeric({ label, increment }) {
        return(
            <>
              <label>{label}</label>
              <button onClick={increment}>Click</button>
            </>
        )
    }
    

    Remember,

    <div prop1={'asdf'}></div>
    

    is actually translated to

    React.createElement('div', {prop1: 'asdf'})