santoku
santoku

Reputation: 3427

react how to pass props to inline css style in components

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

Answers (2)

Dan Atanasov
Dan Atanasov

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 divs 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

Vencovsky
Vencovsky

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

Related Questions