Add CSS styles in ReactJS page

The more the UI is eye pleasant, the more user can feel comfortable while using the website. And we can make the website’s UI more eye pleasant by adding styles. In this article, we will talk about,

  • Setting dynamic inline styles
  • Setting dynamic classes

Setting dynamic inline styles

The inline styles take higher priority. Whatever class we use in an HTML tag, it will take its code after rendering inline styles; if there are any.

  • Create a form with an input tag and a button in it,
<div className="w-2/3 mx-auto">
     <form className="card-body  my-20 p-0">

       <div className="form-control items-center lg:items-start">
         <input required type="text" placeholder="text" className="input input-bordered w-full max-w-md " />
       </div>


       <div className="form-control items-center lg:items-start mt-6">
         <button type="submit" className="btn btn-sm w-full max-w-md">Submit</button>
       </div>
     </form>

   </div>

Note: Please read this article to know about creating a react project with Tailwind CSS setup.

  • Declare a state to get the input values and an onChange() hander,
import React, { useState } from "react";
const App = () => {
  const [textvalue, setTextValue] = useState('');
  return (
    <div className="w-2/3 mx-auto">
      <form className="card-body  my-20 p-0">

        <div className="form-control items-center lg:items-start">
          <input onChange={e => setTextValue(e.target.vlaue)} required type="text" placeholder="text" className="input input-bordered w-full max-w-md " />
        </div>

        <div className="form-control items-center lg:items-start mt-6">
          <button type="submit" className="btn btn-sm w-full max-w-md">Submit</button>
        </div>
      </form>

    </div>
  );
}

export default App

This way, we will get the input values while typing.

  • Set an onSubmit() handler and declare a function for it in the form.
import React, { useState } from "react";
const App = () => {
  const [textvalue, setTextValue] = useState('');

  const handleFormSubmit = e => {
    e.preventDefault()
  }
  return (
    <div className="w-2/3 mx-auto">
      <form onSubmit={handleFormSubmit} className="card-body  my-20 p-0">

        <div className="form-control items-center lg:items-start">
          <input onChange={e => setTextValue(e.target.vlaue)} required type="text" placeholder="text" className="input input-bordered w-full max-w-md " />
        </div>

        <div className="form-control items-center lg:items-start mt-6">
          <button type="submit" className="btn btn-sm w-full max-w-md">Submit</button>
        </div>
      </form>

    </div>
  );
}

export default App
  • Declare a state for the validation of the input field
  const [isValid, setIsValid] = useState(true)

Our goal is, if the input field is empty we will set the input field as an invalid one and add some dynamic styles based on this.

  • Write a condition to check the input length of the input field
if (!textvalue.trim().length) {
  setIsValid(false)
}

We are checking if the input field is empty or not. If it is empty it will give a false result. If it is false, then isValid state value will be set as false.

const handleFormSubmit = e => {
    e.preventDefault()
    if (textvalue.trim().length === 0) {
      setIsValid(false)
    } else {
      setIsValid(true)
    }
  };

If the input value is empty then after form submission we will get an error, else there will be no error.

  • Write inline styles based on this condition,
<input style={{ backgroundColor: isValid ? 'gray' : 'salmon' }} onChange={e => setTextValue(e.target.value)} type="text" placeholder="text" className="input input-bordered w-full max-w-md " />

In react, inline styles can be added as an object. Hence, we are checking if the isValid state is true or false. If false, the background color will be changed to salmon.

As it is an empty field, after clicking in submit button background color has been changed.

As the input value is not empty, the background color turns gray.

We also can set dynamic classes based on this isValid condition in react.

Setting dynamic classes

  • Go to the App.css file (this app.css file will be created by default after the creation of the react project. Please read this article to create a react project)

  • Add two different styles for two different classes here,
.valid-field {
  background-color: gray;
}

.invalid-field {
  background-color: salmon;
}
  • Add the dynamic classes to the input field, dynamically.
<input onChange={e => setTextValue(e.target.value)} type="text" placeholder="text" className={`input input-bordered w-full max-w-md ${isValid ? 'valid-field' : 'invalid-field'}`} />

Here we have added dynamic classes inside the back tic sign (“). After that, we added curly braces. And inside the curly braces, we have added dynamic classes with the doller sign ($). If the field is valid, then the valid-field class will be active, else invalid-field class will be active.

import React, { useState } from "react";
import './App.css'
const App = () => {
  const [textvalue, setTextValue] = useState('');
  const [isValid, setIsValid] = useState(true)
  const handleFormSubmit = e => {
    e.preventDefault()
    if (!textvalue.trim().length) {
      setIsValid(false)
    } else {
      setIsValid(true)
    }
  };
  return (
    <div className="w-2/3 mx-auto">
      <form onSubmit={handleFormSubmit} className="card-body  my-20 p-0">

        <div className="form-control items-center lg:items-start">
          <input onChange={e => setTextValue(e.target.value)} type="text" placeholder="text" className={`input input-bordered w-full max-w-md ${isValid ? 'valid-field' : 'invalid-field'}`} />
        </div>

        <div className="form-control items-center lg:items-start mt-6">
          <button type="submit" className="btn btn-sm w-full max-w-md">Submit</button>
        </div>
      </form>

    </div>
  );
}

export default App

As the input field is empty, we are getting salmon color as the background color.

And now the field is not empty. We are getting gray background color.

This is how we can add dynamic inline styles and dynamic classes in react.