Home > Mobile >  How to pass a css inside an html tag in styled components? (react)
How to pass a css inside an html tag in styled components? (react)

Time:12-30

I have a react application where I receive through an API, a category. Within that category, I have "color" where a css color is sent.

In "category" I would like to pass the css color that is sent within the information I receive in the api, so for that I must pass the color within p id="cat" with the "color"

import * as C from './styles';

import { useNavigate } from 'react-router-dom';

const Card = ({img, date, title, category, color, id}) => {  
    const navigate = useNavigate();

    const handleSinglePost = () => {
        navigate(`/singlepost/${id}`)
    }

  return (
    <C.Card onClick={handleSinglePost}>
        <C.ImgContainer>
            <img src={img} alt="" />
            <C.Cat>
                <p> {date}</p>
                <p id='cat'> {category}</p>
            </C.Cat>
            <h2>{title}</h2>
        </C.ImgContainer>
    </C.Card>
    )
}

export default Card;

That is, in theory pass color as background-color style of p

something like:

<C.Cat>
  <p> {date}</p>
  <p id='cat'style={background-color: color}> {category}</p>
</C.Cat>

It certainly doesn't work that way, but it's an example of what I'd like it to be and how I've tried to illustrate

CodePudding user response:

Try to write:

<p id='cat'style={{backgroundColor: color}}> {category}</p>

style property accepts an object with camel-cased css properties.

  • Related