Ad

`react.cloneElement` Ignores ClassName, How Can I Give Something A ClassName?

- 1 answer

Reading through the docs, it seems that the now deprecated cloneWithProps merged the classNames, but cloneElement ignores the className that's passed in

https://jsfiddle.net/z12hc5er/1/

var Foo = function () {
    return <div className="shows-up">Hello World</div>;
};

var Bar = function () {
    return React.cloneElement(<Foo/>, {className: 'ignored'});
};

ReactDOM.render(
    <Bar/>,
    document.getElementById('container')
);

Is there any way to influence the className of a cloned element?

Ad

Answer

className is an attribute of a particular element in Foo, what if you had multiple elements with classNames?

The second parameter is for passing props. Props are just a way of passing data to the component, react doesn't assume how you want to use them, so you'd have to explicitly tell it, e.g:

var Foo = function (props) {
    return <div className={props.className || 'shows-up'}>Hello World</div>;
};

var Bar = function () {
    return React.cloneElement(<Foo/>, {className: 'not-ignored'});
};

ReactDOM.render(
    <Bar/>,
    document.getElementById('container')
);

I guess they decided that doing something special with style and className (and ignoring key and ref) was too opinionated in cloneWithProps.

Edit: Looking here it looks like it was actually done of optimisation reasons: https://facebook.github.io/react/blog/2015/03/10/react-v0.13.html

Ad
source: stackoverflow.com
Ad