Ad

How To Map Through Component Right?

- 1 answer

I'm a newbie and I start to learn react js. So now I have component which has svg icons inside:

export default class IconPick extends Component {
    render() {
        const { icon, size = 20, className, ...extraProps } = this.props;
        let path;
        let viewBox;

        switch ( icon ) {
            case 'envelope':
                viewBox = '0 0 512 512';
                path = 'M502.3...';
                break;
            case 'globe':
                viewBox = '0 0 496 512';
                path = 'M336.5...';
                break;
            case 'plus':
                viewBox = '0 0 24 24';
                path = 'M24...';
                break;
        }
        if ( ! viewBox ) {
            return null;
        }
        if ( ! path ) {
            return null;
        }

        const iconClass = [ 'myicon', 'myicon-' + icon, className ].filter( Boolean ).join( ' ' );

        return (
            <SVG
                aria-hidden
                role="img"
                focusable="false"
                className={ iconClass }
                xmlns="http://www.w3.org/2000/svg"
                width={ size }
                height={ size }
                viewBox={ viewBox }
                { ...extraProps }
            >
                <Path d={ path } />
            </SVG>
        );
    }
}

So everything working fine like that:

<IconPick icon={'globe'} />

So now I want to display every icon, but I don't know how to map right. I can do something like this, but this is not practical:

<div>
    <IconPick icon={'globe'} />
    <IconPick icon={'envelope'} />
    <IconPick icon={'plus'} />
</div>

Can you help me, please? Thanks in advance.

Ad

Answer

JSX has a slight different syntax. Try this:

<div>
    {["globe", "envelope", "plus"].map(icon => (
      <IconPick key={icon} icon={icon} />
    ))}
 </div>

More on that here

Ad
source: stackoverflow.com
Ad