React Fundamentals: Styling And Handling Forms

Full-Stack Developer, Entrepreneur and Co-Founder of Coderplex.
Building https://coderplex.in
Checkout my portfolio at https://bhanuteja.dev
Search for a command to run...

Full-Stack Developer, Entrepreneur and Co-Founder of Coderplex.
Building https://coderplex.in
Checkout my portfolio at https://bhanuteja.dev
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...
Bhanu Teja Pachipulusu, I think the series is going really strong.. keep it up!
In this series, I will write different blog posts based on workshop content from [Kent C. Dodds](https://kentcdodds.com)'s [EpicReact.Dev](https://epicreact.dev) as I go through it.
Hello World 👋 Hooks are special types of functions in React that you can call inside React functional components. They let you store data, add interactivity, and perform some actions, otherwise known as side-effects. Below are the most common hooks ...
Authored in connection with the Write With Fauna program. Table of Contents Authentication Setting up Fauna in Next.js Installing Fauna Setting up Migrations Tool Authentication and Authorization in Fauna Next.js Serverless Function Setup for Fa...

I wanted to start blogging in Aug of 2020. I decided to use @hashnode for my blog. It was the best decision that I made. I wrote 27 technical articles so far. Most of them are about frontend web development. A thread 🧵 about each of these articles i...

Next.js has become my go-to framework for almost every project that I make. So, I made a starter template that I can just use and get started easily. In this article, I will show you how to use the starter template that I made and deploy it with Verc...

In this article, I will list out all the git commands that I use very frequently. This is not in any way a complete list, just the commands that I use very often. This is intended to be used as a quick reference to perform an action that you want. ...

In this article, we will see the order in which different useEffect callbacks and cleanups happen. We will also see how it differs when the app mounts, unmounts, updates. This image is taken from https://github.com/donavon/hook-flow. I took the ex...

Bhanu Teja Pachipulusu's blog
29 posts
Developer, Indie Maker and Blogger. Currently building MDX.one
Checkout my portfolio
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.Devvideo 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.
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.
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:
background-color in CSS is backgroundColor in the style object.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>
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;
}
The example used in this section is directly taken from React Fundamentals Workshop by Kent C. Dodds's
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:
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.
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.
Note:
useState also takes the initial value of the state as its single argument.Example:
const [count, setCount] = useState(0)
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:
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.useState hook in more detail in later articles.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.
This is the last article where we learn about React Fundamentals. The next article in this series is about different hooks in React.
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.