Chris Wilson Chris Wilson - 23 days ago 6
Javascript Question

Interpolating a JavaScript expression into an object which is a React prop

I have the following code which doesn't work

tabs.map(tabs, (tab) => (
<Tab options={{'option':{tab.key === 'value'}}}>
...
</Tab>
));


My problem is
some.key
, which is throwing an error because I'm obviously not interpolating this expression properly.

Can anyone tell me what I need to do please? I can't do it in a separate expression because the
options
is dependant on the
tab
being mapped over.

Answer

This is not valid syntax for an object literal. Also, assuming that tabs is an iterable, the first parameter of map() should be the mapping function.

The following should work:

tabs.map(tab => (
    <Tab options={{option: tab.key === 'value'}}>
        ...
    </Tab>
));

To make it cleaner, define your options before rendering the component:

tabs.map(tab => {
    const options = {option: tab.key === 'value'};

    return (
        <Tab options={options}>
            ...
        </Tab>
    );
});