Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React passing additional classNames to child component in addition to other props

Tags:

reactjs

I'd like to pass additional classNames into a child component, and also pass down any other props.

For example:

class Parent extends Component {
    render() {
        <Child
            className="parent-class"
            flavor="chocolate"
        />
    }
}

class Child extends Component {
    render() {
        <div className="child-class" {...props}>

        </div>
    }
}

In this case, I would like the Child component div to have the "flavor" prop, and also have both classes "parent-class" and "child-class". However as it is, the className="child-class" will be overwritten by {...props}.

The only workaround I can think of is putting the {...props} before the className in the Child component:

<div {...props} className={`child-class ${props.className}`}>

Is this the only workaround? Or is there a cleaner solution?

like image 692
Andrew Avatar asked Dec 11 '18 19:12

Andrew


1 Answers

I typically use the classnames package and the rest operator for things like this.

import classNames from 'classnames';

class Parent extends Component {
    render() {
        <Child
            className="parent-class"
            flavor="chocolate"
        />
    }
}

class Child extends Component {
    render() {
        const { className, ...rest } = this.props;
        const childClassNames = classNames('child-class', className);

        return (
            <div className={childClassNames} {...rest}>
            </div>
        );
    }
}

You can call rest whatever you like, e.g. ...props will create an object variable called props which would contain everything from this.props except for className.

Also, the classnames package is very widely used, and lets you do other cool things like conditionally include class names.

like image 87
Bryan Downing Avatar answered Oct 23 '22 05:10

Bryan Downing