Reputation: 581
I have a parent component and some child components and I want send function from parent to child and in child component call it.
parent:
const buttons = [
{
key: 'driveFormulaButton',
title: 'Drive Formula',
icon: faGitAlt,
type: 'primary',
function: (message) => {
console.log('fasf');
},
},
];
return (
<Child
buttons={buttons}
></Child>
);
Child Component:
const Child = (props) => {
return (
<Button size="small" type={props.buttons.type} onClick={props.buttons.function('test')}> //not work after set propery
<FontAwesomeIcon icon={props.buttons.icon} />
</Button>
);
});
Upvotes: 0
Views: 75
Reputation: 1375
Well you send an array of buttons as props to you single Child-Component. Then you try to access a single object of that array in the Button-Component. This cant work. Better map throught you button in the parent and send a single button down as props:
const buttons = [{*Button1*, *Button2*}]
render(
{buttons.map((button) => <Child button={button}>)}
)
Then you can access the button as you intend to in your Child-component.
Next time you ask a question please provide better information to what you are actually trying to do and what the problem (e.g. error message) is. Ask specific questions. This makes it easier to answer you.
Upvotes: 0
Reputation: 510
Your parent component needs to map through the children components:
Parent
function renderChildren() {
const buttons = []; // <--- populate this as in your OP
return buttons.map((button) => {
return (
<Button size="small" type={button.type} onClick={() => button.function('test')}>
<FontAwesomeIcon icon={button.icon} />
</Button>
)
})
}
return (
<>
{renderChildren()}
</>
);
Upvotes: 0
Reputation: 53874
You call the function instead of passing it an onClick
callback and you should map the buttons
array:
const Child = (props) => {
return props.buttons.map((prop) => (
<Button
key={prop.key}
size="small"
type={prop.type}
onClick={() => prop.function("test")}
>
<FontAwesomeIcon icon={prop.icon} />
</Button>
));
}
Upvotes: 2