React Fundamentals: Styling And Handling Forms

Subscribe to my newsletter and never miss my upcoming articles

Hello World 👋

This is the 6th article of the series My Review of Kent C. Dodds's EpicReact.Dev. Please note that this blog post series is just my review of the EpicReact.Dev workshop material. I am just trying to explain what I learned and understood in my own way. This is not in any way officially associated with Kent C. Dodds or EpicReact.Dev. You would learn a lot more when you actually go through the EpicReact.Dev video explanations and workshop material yourself. The workshop material is also self-paced and open source. So, if you want to do the workshop yourself, you can go to React Fundamentals Workshop Repo and follow the instructions there.

In this article, you will learn about how to do styling in React. You will also learn how to handle forms in React.

Styling

In React, there are primarily two ways to style the elements. One is through inline CSS and the other is to just add a className and style it in an external CSS file.

Inline CSS

In HTML, you can add inline styles to elements by adding your styles as a string to the style attribute.

<div style="color: red; font-style: italic;">Red Italic Text</div>

In React, you would add your styles to the style prop, but instead of a string, the style prop accepts a Style Object.

Note:

  • The properties in the style object are camel-cased.
    • For example, background-color in CSS is backgroundColor in the style object.
    • Know More
const elementStyle = {
    color: 'red',
    fontStyle: 'italic'
}
<div style={elementStyle}>Red Italic Text</div>

You can even inline elementStyle if you like

<div style={{ color: 'red', fontStyle: 'italic' }}>
    Red Italic Text
</div>

Regular CSS

You can add styles to the elements by adding the className attribute and then styling it in an external CSS file.

<div className="container">Hello World</div>
.container {
    margin: 0 auto;
    background-color: red;
}

Handling Forms

The example used in this section is directly taken from React Fundamentals Workshop by Kent C. Dodds's

Using event.target

Consider the following form

<form>
  <div>
    <label htmlFor="usernameId">Username:</label>
    <input id="usernameId" type="text" name="username" />
  </div>
  <button type="submit">Submit</button>
</form>

Now handling forms in React is very similar to how we do in normal javascript. You just define a submit handler and then assign it to the onSubmit event of the form.

<form onSubmit={handleSubmit}>
    ...
    ...
    ...
</form>
function handleSubmit(event) {
    // This prevents the default behaviour of form submission
    // If you don't add this, the page will be refreshed 
    event.preventDefault()

    /** 
     You can get the value of username in one of the following ways.        
        (through the position of input)
        -> event.target.elements[0].value

        (through id)
        -> event.target.elements.usernameId.value

        (through name)
        -> event.target.elements.username.value
    **/

   // Do whatever you want with the username
}

Notes:

Using Refs

There is another way to get the reference to an element in React - using Refs. Refs are special objects in react that stay consistent between rerenders of the component and also changing it will not cause the component to rerender.

You can create a Ref using React.useRef()

const myRef = React.useRef()

Refs will have a current property which contains the value of ref. If you assign a ref to a React element, ref.current will automatically have the reference to the object.

For example

<input ref={myRef} />

Now myRef.current will have reference to that input element.

Let's make use of ref to get the username in our form.

function UsernameForm() {
  const usernameInputRef = React.useRef()

  function handleSubmit(event) {
    event.preventDefault()
    // usernameInputRef.current.value will have the value of the input
  }

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="usernameInput">Username:</label>
        <input id="usernameInput" type="text" ref={usernameInputRef} />
      </div>
      <button type="submit">Submit</button>
    </form>
  )
}

Go through useRef - official docs to learn more about refs.

Using useState

This is the most common way that is used to handle forms in React.

We store the value of the input in a state variable and then add an onChange handler to the input which updates the state variable.

In React, there is a special function called useState which you can use to handle state. It returns an array of two values.

  1. The value of the state
  2. A function to update the value of the state

Note:

  • useState also takes the initial value of the state as its single argument.

Example:

const [count, setCount] = useState(0)
  • Here count hold the value of the state.
  • setCount is a function that can update the value of count.
  • 0 is the initial value of count.

Let's use this to handle forms.

function UsernameForm() {
  const [username, setUsername] = useState('')

  function handleSubmit(event) {
    event.preventDefault()
    // 'username' will have the value of the input
  }
  function handleChange(event) {
    setUsername(event.target.value)
  }

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label htmlFor="usernameInput">Username:</label>
        <input 
            id="usernameInput" 
            value={username} 
            type="text" 
            onChange={handleChange} 
        />
      </div>
      <button type="submit">Submit</button>
    </form>
  )
}

Note:

  • The reason why we are using useState to handle the state of the application and not normal variables is that if we have a normal variable that holds state, changing it will not cause the component to rerender. So, even though the value changes, we can't see the change. But if we use the function that we got from useState to update the state, then React knows that the state of the application is changed, and it automatically rerenders the component.
  • We will learn about useState hook in more detail in later articles.
  • This type of input where the value of input is set through value attribute and then updating of that value is handled with onChange event handler is called controlled input.

Go through official docs to learn more about handling forms in React.

What's Next

This is the last article where we learn about React Fundamentals. The next article in this series is about different hooks in React.

Until Next Time 👋


If this was helpful to you, Please Like and Share so that it reaches others as well. To get email notifications on my latest articles, please subscribe to my blog by hitting the Subscribe button at the top of the page. You can also follow me on Twitter @pbteja1998.

Skay's photo

Great Series Bhanu Teja Pachipulusu... I've bookmarked all of them... will be definitely going through it, since I'm getting into the thick of things with React...

Tapas Adhikary's photo

Bhanu Teja Pachipulusu, I think the series is going really strong.. keep it up!

Vamsi Rao's photo

Great series! Bookmarked it for later :)