Search code examples
javascripthtmlcssreactjsinline-styles

React - How to avoid this kind of inline styling


At the top of my functional component, these values are set which are not used only in styles, and that's what's bothering me:

const testWidth = 100;
const testHeight = 100;

I use some of those variables in my styles...

I would like to move my styles to another file which would hold this styling and would be related with some class name for example '.divWrapperStyle' but I'm not sure how can I interact with this variable 'testWidth'

<div
style={{
  borderBottom: 0,
  width: `${testWidth}px`,
  width: 'auto',
  paddingRight: 0,
  paddingLeft: 0,
  paddingTop: 20,
}}
>

So I could create a something in external .scc file like this:

.wrapper{
    borderBottom: 0,
    paddingRight: 0,
    paddingLeft: 0,
    paddingTop: 20,
 }

And I might use something like this after importing that file:

 <div className="wrapper> 

but what about width? How could I include width with that value from testWidth variable...?

So that variables which are used in CSS are problematic for me :/

How to deal with this?

Thanks


Solution

  • Why don't you simply create a .JS file, for example: style.js and do the following:

    const testWidth = 100;
    const testHeight = 100;
    
    export default const styles = {
       divWrapperStyle: {
         borderBottom: 0,
         width: testWidth, // use your variable here
         width: 'auto',
         paddingRight: 0,
         paddingLeft: 0,
         paddingTop: 20,
       }
    }
    

    and then in your functional component you import it doing:

    import styles from '{pathToStyle.jsFile}';
    

    and use it:

    <div style={styles.divWrapperStyle}>
    

    This is the most easy and efficient way of doing it in my opinion. With this approach you can make everything dynamic later and no need of external libraries.