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.
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.
Share Improve this question asked Jun 26, 2019 at 14:32 santokusantoku 3,44710 gold badges50 silver badges82 bronze badges 1- Possible duplicate of stackoverflow./a/37827390/2427237 – nimsrules Commented Jun 26, 2019 at 14:36
2 Answers
Reset to default 4Passing 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" }}
/>
);
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"
}} />
}