Reputation: 3427
I need to draw some colored squares and use props to control the color of these squares.
The current code is not working
import React from "react";
class SketchExample extends React.Component {
constructor(props) {
super(props);
}
render() {
const { color } = this.props;
return <div style={{ color: this.props.color, width: "36px", height: "36px" }} />; } }
export default SketchExample;
And the app.js file
import React from "react";
import ReactDOM from "react-dom";
import SketchExample from "./SketchExample";
function App() {
return (
<div className="App">
<SketchExample color={{ r: "201", g: "112", b: "19", a: "1" }} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Which part went wrong? Thanks.
Upvotes: 2
Views: 6409
Reputation: 61
From a quick glance of your code I can see you pass a color
prop to SketchExample
which is an object with props such as r
and g
and etc. Yet inside SketchExample
the div
s style.color
is the object, not the actual color. Try something like this:
render() {
const { color } = this.props;
return <div style={{
color: `rgba(${color.r},${color.g},${color.b},${color.a})`,
width: "36px",
height: "36px"
}} />
}
Upvotes: 2
Reputation: 31565
Passing color
will make the text inside the div
of that color.
What you need it backgroundColor
to make "colored squares".
Also, you can't pass an object to a styles, it need to be a string.
return (
<div
style={{ backgroundColor: `rgba(${Object.values(this.props.color).join(", ")})`, width: "36px", height: "36px" }}
/>
);
Upvotes: 4