Reputation: 14328
I have a React component, a button, and I need to set the background-color
of a child element to the color
of the button. I know that you're not supposed to call this.refs.myElement.getDOMNode()
in the render()
function, so I'm not sure how I'm supposed to lay this out.
At the moment, my code looks like this:
import React from 'react';
import { Button, Glyphicon } from 'react-bootstrap';
import classnames from 'classnames';
export default class GlyphButton extends Button {
constructor(props) {
super(props);
}
render() {
let {
glyph,
className,
children,
...props
} = this.props;
return (
<Button ref='btn' {...props} className={classnames([className, 'glyph-button'])}>
<Glyphicon glyph={glyph} />
{children}
</Button>
);
}
}
I need to do something like this:
let color = this.refs.btn.style.color;
return (
<Button ref='btn' ...>
<Glyphicon glyph={glyph} style={{backgroundColor: color}} />
{children}
</Button>
);
Unfortunately, this.refs
hasn't been populated yet.
In case you're curious, the reason I'm doing this is because I'm using Glyphicon's free version PNGs for some icons, which are all black on a transparent background, and I'm using:
glyphicon.glyphicon-playing-dice:before {
content: "";
width: 20px;
height: 20px;
-webkit-mask-size: 100%;
-webkit-mask-image: url(/img/glyphicons/glyphicons-playing-dice.png);
display: block;
}
to make it act like a font icon. This class will make the element's background-color
the color of the displayed icon.
Upvotes: 2
Views: 2388
Reputation: 3056
You can set color
as a state and change it in componentDidMount
stage.
getInitialState: function(){
return {bgColor: ''}
},
componentDidMount: function(){
var color = React.findDOMNode(this.refs.btn).style.color;
this.setState({bgColor : color});
}
Because React recommend us that :
your first inclination is usually going to be to try to use refs to "make things happen" in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy.
Upvotes: 1