score:39

Accepted answer

Pass in the component constructor instead of an instance:

class Menu extends React.Component {
    render() {
        return(
            <div className="Menu">
                <MenuItem icon={MdInbox} />
                <MenuItem icon={MdDrafts} />
                <MenuItem icon={MdTrash} />
            </div>
        );
    }
}

The child class:

class MenuItem extends React.Component {
    render() {
        // This constant must begin with a capital,
        // it’s how React distinguishes HTML elements from components.
        const Icon = this.props.icon;
        return(
            <div className="MenuItem">
                <Icon size={24} />
            </div>
        );
    }
}

score:0

You can also just pass the component and props to the child elemnt, fully destructure your component and props, then render it as a JSX element. You then can spread your props into the passed component. This way your child component reusable and you can change its props from the parent component.

class Menu extends React.Component {
        render() {
            return(
                <div className="Menu">
                    <MenuItem Icon={MdInbox} size={24}/>
                    <MenuItem Icon={MdDrafts} size={24} />
                    <MenuItem Icon={MdTrash} size={24}/>
                </div>
            );
        }
    }

The child class:

    class MenuItem extends React.Component {
        render() {
            // This constant must begin with a capital,
            // Use JS ...rest operator to seperate Icon from remaining props
            const {Icon, ...remainingProps} = this.props;
            return(
                <div className="MenuItem">
                    <Icon {...remainingProps}/>
                </div>
            );
        }
    }
}

score:15

You can set icon size with React.cloneElement API

class MenuItem Extends React.Component {
    render() {
        return(
            <div className="MenuItem">
                {React.cloneElement(this.props.icon, { size: 24 })}
            </div>
        );
    }
}

Related Query

More Query from same tag