We can use className prop on any HTML element but not an a custom react component. Requesting to support this feature as it simplifies the component usage when there is a need to apply additional styles without having to wrap the component in an external DIV.
//MyComponent
render() {
return <div className="message">Hello!</div>;
}
//expected usage
<MyComponent className="message--blue"/>
should render
<div className="message message--blue">Hello!</div>
This affect can be achieved by a mixin but non-mounted tests cannot use this.props.className to find the components.
componentDidMount() {
if (this.props.className) {
ReactDOM.findDOMNode(this).classList.add(this.props.className);
}
}
@cliren I feel this can be added directly in the component itself. Or am I missing anything ?
import React from 'react';
import {render} from 'react-dom';
const MyComponent = (props) => {
let {
className,
...otherProps
} = props;
let classNames = ['message', className].join(' ');
return (
<div className={classNames} {...otherProps}>Hello World</div>
);
}
render(<MyComponent className="message--blue" />, document.getElementById('app'));
I appreciate the thought but we aren't going to do conditional merging of any props. It's up to each composite component to decide how it wants to handle props in their implementation. A couple examples: MyComponent could have an implementation that works on React Native where className doesn't mean anything. Or MyComponent is some sort of course scheduling component and className is actually referring to a course's name. There's also the case where className is used not on the root node in the composite but on some other child.
(For some historical context, we had a helper called transferPropsTo a few years ago that did exactly this thing for className. It proved to be confusing and we removed it.)
Thanks @zpao, good reasons why not use it especially the when className needs to be applied to a some other child within the composite. @gaearon I didn't know transferPropsTo existed before, thanks for pointing it out. It might be a little confusing initially for the said reasons but for the web react it felt like the perfect JSX convention.
Most helpful comment
@cliren I feel this can be added directly in the component itself. Or am I missing anything ?
http://www.webpackbin.com/VJL6WYD8b