Best Practices for inline style


(Wanderley Souza) #1

Hi React people! How are you?
I’m new to React and I’m already amazed on how interesting things get going while creating Web apps with React.
In “normal” html programming it’s usual to rely on “grid frameworks” for helping positioning HTML objects on browser.
In the React world is it a good practice to use component’s properties to set this attributes?
Le’ts say I have a Button and an Input components, is there any problem to pass width, height as properties when creating the component?

Something like:


By doing this, I’m able to place the html input wherever I want in the web PageContainer.

Best Regards


(Steven Land) #2

Although it is possible to implement inline styles in your components, I believe it is not the best practice:

<div style={{ width: "220px"  }}>
    // Button/Input here...
</div>  

Instead you should probably implement a style class:

<div className="formContainer">
    // Button/Input here...
</div>

Then following this practice you can dynamically set the style class via props passed into the component:

<div className={props.cssClass}>
    // Button/Input here...
</div>

(Wanderley Souza) #3

Thank you for answering. Seems really more interesting thinking about cssClass as props.


(Johnnysprinkles) #4

I’ll often pass through the style to the top-level element to make style overrides easier. Maybe you have something like this:

// facebook-login-button.js
render() {
  return (
    <button style={{
      backgroundColor: 'blue',
      color: 'white',
      ...this.props.style
    }}>
      Login with Facebook
    </button>
  );
}

Then you can mix in styling such as:

<FacebookLoginButton style={{padding: '5px'}} />

(Richard Zhang) #5

I always create ‘theme’ object to hold styles. For example for new app created by create-react-app you can replace css file with this:

const AppStyle = {
    app: {
        textAlign: 'center'
    },
    logo: {
        animation: 'App-logo-spin infinite 20s linear',
        height: '80px'
    },
    header: {
        backgroundColor: '#222',
        height: '150px',
        padding: '20px',
        color: 'white'
    },
    title: {
        fontSize: '1.5em'
    },
    intro: {
        fontSize: 'large'
    },
    content: {
        padding: '20px'
    }
}