Evanss
Evanss

Reputation: 23613

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>
    )
}

Upvotes: 1

Views: 271

Answers (1)

user9408899
user9408899

Reputation: 4540

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'})

Upvotes: 3

Related Questions