Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass nested styling to a component in React

Tags:

css

reactjs

antd

I'm using this card component, and I'd like to build on top of it. More specifically, I'd like to inline change the background color of titles. The way I though of it, it would look something like this:

<Card title='Produção e reembolso' style={{
  ant-card-head: {
    backgroundColor: '#232323'
  }
}} >
  <div> R$ {productionAmount} </div>
</Card>

This doesn't work, as React thinks ant-card-head is a property name. Is there a way to do this, or I'll have to use/create a different component?

Edit

Rendered HTML looks like this

<div class="ant-card ant-card-bordered">
  <div class="ant-card-head">
    <h3 class="ant-card-head-title">Produção e reembolso</h3>
  </div>
  <div class="ant-card-body">
    <div><!-- react-text: 150 --> R$ <!-- /react-text --></div>
  </div>
</div>
like image 983
iagowp Avatar asked Jun 28 '17 15:06

iagowp


People also ask

Can you add style to React component?

Sharing styles across many React components The style objects and the components do not have to be in the same file. We can create a separate . js file for our styles, export these styles, and then import them into the component where we want to use them.

Can I pass Props to styled component?

Props can be passed to styled components just as they are with regular React components (class or functional). This is possible because styled components are actually React components. styled-components creates a React component, which renders an HTML tag corresponding to the property in the styled object.

Can React components be nested?

In React, we can nest components inside within one another. This helps in creating more complex User Interfaces. The components that are nested inside parent components are called child components. Import and Export keywords facilitate nesting of the components.


1 Answers

If you want to have a common object having styles and pick up stuff from there, you have to declare stuff separately and use.

const AllStyles = {
  "ant-card-head": {
    backgroundColor: '#232323'
  },
  "another-thing": {
    backgroundColor: '#ff00aa'
  }
};
<Card title='Produção e reembolso' style={AllStyles["ant-card-head"]} >
<AnotherElem title='Produção e empréstimo' style={AllStyles["another-thing"]} >

If you just want to inline styles only for this element you do this

<Card title='Produção e reembolso' style={{
  backgroundColor: '#232323'
}} >
like image 152
Aftab Khan Avatar answered Nov 10 '22 22:11

Aftab Khan