Ai Santos

@asantos3026

Styling React Elements

Fourth installment of my series for junior developers. About me, I come from a non-traditional Computer Science background, am an activist and advocate fighting for diversity and inclusion in the technology space. I blog about technical topics related to Front End Development, JavaScript, ReactJS and tech inclusion.

Whoever said CSS was easy is either crazy…or has been writing it for a LONG time.

I am going to show you 3 ways to style your React component.

Method #1

The first way is to pass your style your component inline.

<input style={{backgroundColor: 'blue'}} type="text" />

Camel Case your CSS attribute and then assign it with a string value.

Method #2

The second way is to assign your style to a variable and then pass that variable into your component.

const inputStyle = {
  color: 'blue';
}

Then pass that variable as a prop into the component.

<form onSubmit={this.handleSubmit}>
   <label>
     Name:
     <input style={inputStyle} type="text"   
        value={this.state.value} onChange={this.handleChange} />
   </label>
   <input type="submit" value="Submit" />
</form>

The correct syntax for inline styling your React component is

Method #3

The third way and what I had to implement is using SASS. This method is fairly straightforward but when you’re working with modular code, things can get super nested. Inside its parent component, it is being passed the following props: label , field , id

<BirthDateInput
  label="Date of Birth"
  field={fields.userBirthDate}
  id="userBirthDate"
/>

The child component looks like:

<div className={formInputContainer}>
  <label htmlFor={id}>Date</label>
  <div className={date}>
    <div>
      <SelectInput
        s={s}
        id={`${id}-${DATE_KEY_MONTH}`}
        field={emulateField(DATE_KEY_MONTH)}
        values={getMonths()}
        errorInline={this.props.errorInline}
        funPlaceholder={this.props.funPlaceholder}
        placeholder={this.props.monthPlaceholder}
      />
    </div>

There’s a lot of extraneous code inside the child component but what’s most important to notice is its nesting. In your separate SASS stylesheet, we can see that the <SelectInput /> is being styled under .birthDate .

.birthDate {
  div:last-child .formInputContainer {
    select {
      color: 'black';
    }

    select[name^='userBirthDate'] {
      color: 'grey';
    }
  }
}

The second line in the SASS code above allows you to target the text inside the <SelectInput />. So why are we styling it twice above? The <SelectInput /> has a placeholder and the actual text that the user inputs.

The line select { color: 'black';} targets the user input text. Finally, the line select[name^='userBirthDate'] { color: 'grey';} targets the placeholder text inside the <SelectInput /> .

More by Ai Santos

Topics of interest

More Related Stories