React Fundamentals: Styling And Handling Forms
Tags: react, javascript, codenewbie
Published: 2020-10-22 08:55:52

## Hello World 👋
> This is the 6th article of the series [My Review of Kent C. Dodds's EpicReact.Dev](https://hashnode.com/series/my-review-of-kent-c-doddss-epicreactdev-ckfv4gidh08efu9s1408v8tgp). Please note that this blog post series is just my review of the [EpicReact.Dev](https://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](https://epicreact.dev) or [EpicReact.Dev](https://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](https://github.com/kentcdodds/react-fundamentals) 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](#styling)
    - [Inline CSS](#inline-css)
    - [Regular CSS](#regular-css)
- [Handling Forms](#handling-forms)
    - [Using event.target](#using-eventtarget)
    - [Using Refs](#using-refs)
    - [Using useState](#using-usestate)

### 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](https://www.w3schools.com/jsref/dom_obj_style.asp). 

**Note:**
- The properties in the style object are camel-cased.
    - For example, `background-color` in CSS is `backgroundColor` in the style object.
    - [Know More](https://www.w3schools.com/jsref/dom_obj_style.asp)

```js
const elementStyle = {
    color: 'red',
    fontStyle: 'italic'
}
```
```html
<div style={elementStyle}>Red Italic Text</div>
```
You can even inline `elementStyle` if you like
```html
<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.

```html
<div className="container">Hello World</div>
```

```css
.container {
    margin: 0 auto;
    background-color: red;
}
```

----

### Handling Forms
> The example used in this section is directly taken from [React Fundamentals Workshop](https://github.com/kentcdodds/react-fundamentals) by [Kent C. Dodds's](https://kentcdodds.com)

#### 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.

```html
<form onSubmit={handleSubmit}>
    ...
    ...
    ...
</form>
```

```js
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:**
- [Know more about Event.preventDefault](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)

#### 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.
```js
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](https://reactjs.org/docs/hooks-reference.html#useref) 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
1. A function to update the value of the state

**Note:**
- `useState` also takes the initial value of the state as its single argument.

Example:
```js
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.
```js
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](https://reactjs.org/docs/forms.html) 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](https://blog.bhanuteja.dev) by hitting the **Subscribe** button at the top of the page. You can also follow me on Twitter [@pbteja1998](https://twitter.com/pbteja1998).

[![ko-fi](https://www.ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/J3J72JK30)