Web Dev
Web Dev

Reputation: 63

React props for passing color

I have many div elements with same size but with different colors. So I created a component 'Colors.jsx' in which I have the below code

import React from "react";
import "./styles.css";

function Colors(props) {
  return (
    <div className="colors" style={{backgroundColor: {props.color}}}></div>
  );
}

export default Colors;

The problem is I'm getting these errors:

/src/Colors.jsx: Unexpected token, expected "," (6:59)
4 | function Colors(props) {
5 | return (
6 | <div className="colors" style={{backgroundColor: {props.color}}}>
^ 7 | );
8 | }
9 |

4 | function Colors(props) {
5 | return (
6 | <div className="colors" style={{backgroundColor: {props.color}}}>
^ 7 | );
8 | }
9 |

Parsing error: Unexpected token, expected ","
4 | function Colors(props) {
5 | return (
6 | <div className="colors" style={{backgroundColor: {props.color}}}>
^ 7 | );
8 | }
9 | (null)

Upvotes: 4

Views: 14189

Answers (2)

Guillaume Munsch
Guillaume Munsch

Reputation: 1283

Remove the brackets around props.color like this. Add the children to use your component clearly

function Colors(props) {
  return (
    <div className="colors" style={{backgroundColor: props.color}}>{props.children}</div>
  );
}

Then call it like that

<Colors color="#765739">Hello</Colors>

Upvotes: 2

Shubham Verma
Shubham Verma

Reputation: 5054

The issue is here:

<div className="colors" style={{backgroundColor: {props.color}}}></div>

You need to do like this(remove extra currly braces):

<div className="colors" style={{backgroundColor: props.color}}></div>

Upvotes: 5

Related Questions