I have to build a menu screen component that can be used later on easily. The component only has options in a list way.
const options = [
{
text: 'Option 1',
},
{
text: 'Option 2',
},
{
text: 'Option 3',
},
];
and I just map it inside the component.
const Menu = () => {
return (
<div>
{options.map((option, index) => (
<MenuOption text={option.text} index={index} />
))}
</div>
);
};
const MenuOption = ({ text, index }) => {
return (
<div>
<p>{text}</p>
</div>
);
};
So anyone can use this menu component by passing in the options data. What i want is for this component to also run functions corresponding to the option clicked. So we can easily pass the function that needs to be run as a prop to the component. The main question is that how do i relate/map the options with the corresponding function?
NOTE: I can't send the functions with the options data object in the props.
I mean you can just send one callback to the Menu
component:
const Menu = ({ onOptionClick }) => {
return (
<div>
{options.map((option, index) => (
<MenuOption text={option.text} index={index} onClick={onOptionClick} />
))}
</div>
);
};
const MenuOption = ({ text, index, onClick }) => {
return (
<div onClick={() => { onClick(index, text, whatever) }}>
<p>{text}</p>
</div>
);
};