Home > Mobile >  Styling with dynamically used class names and attributes in JS(React)?
Styling with dynamically used class names and attributes in JS(React)?

Time:07-30

I wonder if there is a feasible way to implement something like that. Say, I want to specify padding but I don't want to use inline styling and want to use classes instead. But I also don't want to specify all possible values in CSS.

Like I write:

<Container className="p25 m10" />

what can be rendered to the self-generated classes p25 and m10

<div /> /* Classes p25 and m10 are self-generated and have padding and margin */

or even

<Container p=25, m=10 />

rendered into the same or at least to

<div style="padding: 25px; margin: 10px"/>

CodePudding user response:

I don't see that there is a way to auto-generate a css class. But, this your first option, are classes that represent some kind of pure css style, what you can do is create a class like this:

.p25 {
  padding: 25px;
}
<Container className="p25"/>

Your second option, are props that inside the functional component, through some logic, you will carry out the implementation, for example:

export default function Container({p, m}) {
  return (
    <div style={{padding: `${p}px`}, margin: `${m}px`}></div>
  )
}

CodePudding user response:

install tailwind and config manual stuff into config file.

module.exports = {
  theme: {
    extend: {
      spacing: {
        '25': '25px',
      }
    }
  }
}

then use it this way

<div >
  <!-- ... -->
</div>
  • Related