Reputation: 531
How can we assign a class to the outmost wrapper of a component in React?
For example, I was trying to add class "table" to this "FilterableProductTable" so that the outmost wrapper, "" in this case, can have a class assigned to it?
What I did is to add prop "className={"table"}", but it does not seem to work. When inspected, the outmost div still doesn't have a class.
ReactDOM.render(
<FilterableProductTable className={'table'} products={PRODUCTS} />,
document.getElementById("container")
);
the outer wrapper div still doesn't have a class
Upvotes: 1
Views: 1312
Reputation: 13157
This is completely possible. You must remember that FilterableProductTable
is a Component and doesn't represent a DOM node element, like div
, so you are actually just passing a property called className
to your Component. It is then up to your component to use the passed in property.
For e.g.
class FilterableProductTable extends Component {
render() {
return (
<div className={this.props.className}>
...
</div>
);
}
}
ReactDOM.render(
<FilterableProductTable className='table' products={PRODUCTS} />,
document.getElementById("container")
);
If you notice above I am actually accessing the passed in property called className
via this.props
in the FilterableProductTable
. So any properties you set on a Component when rendering it will be passed into the Component, and then it is up to the Component's own rendering logic how it wants to use those properties.
You could have called the property foo
or whatever too, for e.g.:
class FilterableProductTable extends Component {
render() {
return (
<div className={this.props.foo}>
...
</div>
);
}
}
ReactDOM.render(
<FilterableProductTable foo='table' products={PRODUCTS} />,
document.getElementById("container")
);
Look at the React docs, all the following are HTML Elements natively supported by React: https://facebook.github.io/react/docs/tags-and-attributes.html#html-elements
If you set the className
prop on those items then the class would be attached to them directly. :)
Upvotes: 3
Reputation: 854
On the outermost div of the FilterableProductTable
component you need to include the className
prop:
<div className={this.props.className}>
{...children}
</div>
Upvotes: 2