Learner Learner - 1 month ago 13
React JSX Question

Show icon of its tab

I have an api of tab which has name of tab, id of the tab and id of the icon (its a foreign key). I want to show icon of its tab but how can i show when api is designed in such a way.

api/tab

[
{
"id": 114,
"name": "analytics",
"icon": 2,
},
{
"id": 127,
"name": "share",
"icon": 2,
}


]

api/icon

[
{
"id": 1,
"name": "computer",
},
{
"id": 2,
"name": "insert-photo",
},
{
"id": 3,
"name": "account-circle",
}
]


header.js

componentDidMount() {
this.props.fetchTabs();
}

render() {
const tabs = _.map(this.props.tabs.tabs, (tab) =>
<span className="tab" key={tab.id}>
<a href="">{tab.name}</a>
</span>
);

const mapStateToProps = (state) => ({
fetchIcon: state.fetchIcon,
tabs: state.tabs,
});

function mapDispatchToProps(dispatch) {
return bindActionCreators({
fetchTabs,
}, dispatch);
}


Help me on how to show icon of the tab as they are linked with id?

Error screenshot

when using

const mapStateToProps = (state) => ({
fetchIcon: state.fetchIcon,
tabs: state.tabs.map(tab => ({
...tab, icon: state.fetchIcon.find(icon =>
icon.id === tab.icon)
).name
}),
tabsPost: state.tabsPost
});


enter image description here

Answer

You can un-normalize data in mapStateToProps:

const mapStateToProps = state => ({
    tabs: state.tabs.map(tab => ({
        ...tab,
        icon: state.icons.find(icon => 
            icon.id === tab.icon
        ).name
    })
})

Now tab.icon will be either computer, insert-photo or account-circle in your component.

Edit: after discussion, we have come up with the following code:

const mapStateToProps = state => {
    return {
        tabs: state.tabs.tabs.map(tab => {
            const icon = state.deviceEventOption.find(icon => Number(icon.id) === tab.icon);
            return {
                ...tab,
                icon: icon && icon.name
            };
        })
    };
};
Comments