React Fundamentals: Creating Custom Components
Tags: react, javascript, codenewbie
Published: 2020-10-21 04:56:32

## Hello World 👋

Welcome to the 5th 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.

If you haven't read the previous articles in this series, please go and read them first before you continue. I will add links to the articles below.
1. [Introduction](https://blog.bhanuteja.dev/epic-react-introduction)
1. [Javascript You Need To Know For React](https://blog.bhanuteja.dev/epic-react-javascript-you-need-to-know-for-react)
1. [React Fundamentals - Intro to React Raw APIs](https://blog.bhanuteja.dev/epic-react-react-fundamentals-part-1)
1. [React Fundamentals - Understanding JSX](https://blog.bhanuteja.dev/react-fundamentals-understanding-jsx)

In the previous article, you have learned different things about JSX like converting React.createElement() calls to JSX and vice-versa, interpolation in JSX, spreading props in JSX, etc. In this article, we will learn how to create custom components in JSX.

### Table of Contents
- [Creating Basic Reusable Function](#creating-basic-reusable-function)
- [Using React.createElement](#using-reactcreateelement)
- [Using JSX](#using-jsx)
- [Validation with PropTypes](#validation-with-proptypes)
- [Using prop-types Package](#using-prop-types-package)
- [React Fragments](#react-fragments)

> The examples shown in this article are taken from [Kent C. Dodds](https://kentcdodds.com)'s [React Fundamentals](https://github.com/kentcdodds/react-fundamentals) workshop repo.


### Creating Basic Reusable Function

Consider the following JSX markup.

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

Now, our goal is to avoid the duplication `<div className="message">...</div>`.

Like we normally would do in vanilla javascript, let's create a reusable function that takes the text as an argument and returns the JSX that we need.

```js
function message(text) {
    return <div className="message">{text}</div>
}
```

Now we can write our JSX markup in the following manner.
```html
<div className="container">
    {message("Hello World")}
    {message("GoodBye World")}
</div>
```

Let's refactor this a bit, instead of accepting the string value as an argument, let's pass an object that has a `children` key in it.
```js
function message(props) {
    return <div className="message">{props.children}</div>
}
```

```html
<div className="container">
    {message({children: "Hello World"})}
    {message({children: "GoodBye World"})}
</div>
```

We can even go a step further and destructure the children prop.
```js
function message({children}) {
    return <div className="message">{children}</div>
}
```

```html
<div className="container">
    {message({children: "Hello World"})}
    {message({children: "GoodBye World"})}
</div>
```

### Using React.createElement
Previously we have seen that the first argument of the `React.createElement()` is the type of tag that we want to render.

For example, `React.createElement('div', {}, 'Hello World')` will render `<div>Hello World</div>`.

But, the first argument of the `React.createElement()` will also accept a function as its arguments that generate something renderable like JSX, an expression like string, number, etc. 

So, let's refactor the above code and use `React.createElement()`

```js
function message({children}) {
    return <div className="message">{children}</div>
}
```

```html
<div className="container">
    {React.createElement(message, {children: "Hello World"})}
    {React.createElement(message, {children: "GoodBye World"})}
</div>
```

### Using JSX
In the previous article, we have seen how to convert `React.createElement()` calls to JSX.

For example, JSX for `{React.createElement("div", {children: "Hello World"})}` is `<div>Hello World</div>`

Let's try to use the similar approach to convert `{React.createElement(message, {children: "Hello World"})}` to JSX.

```html
<message>Hello World</message>
```
If we follow the same approach, we would end up with the above JSX markup.

As per our knowledge until now, the above code should work as intended. But it will not. It is because of how babel compiles JSX to React.createElement().

The above JSX will be compiled to `React.createElement("message", {children: "Hello World"})` instead of `React.createElement(message, {children: "Hello World"})`.  Notice the difference. In the first case, the argument is the string `"message"` whereas in the second case, the argument is the reference to the `message` function. 

The way we can achieve this is very simple. We simply have to make the first letter of the name of the function as uppercase.

```js
function Message({children}) {
    return <div className="message">{children}</div>
}
```

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

Now, this `<Message>Hello World</Message>` will be compiled to `React.createElement(Message, {children: "Hello World"})` which is exactly what we need.

Check the below examples to see how Babel compiles each of the JSX formats.

| JSX                    	                | React.createElement()                   	                |
|---------------------------- |------------------------------------------------|
| `<Capitalized />`        	        | `React.createElement(Capitalized)`        	        |
| `<property.access />`    	| `React.createElement(property.access)`    	|
| `<Property.Access />`    	| `React.createElement(Property.Access)`    	|
| `<Property['Access'] />` 	| `SyntaxError`                             	                        |
| `<lowercase />`          	| `React.createElement('lowercase')`        	        |
| `<kebab-case />`         	| `React.createElement('kebab-case')`       	|
| `<Upper-Kebab-Case />`  	| `React.createElement('Upper-Kebab-Case')` 	|
| `<Upper_Snake_Case />`   | `React.createElement(Upper_Snake_Case)`   	|
| `<lower_snake_case />`   	| `React.createElement('lower_snake_case')` 	|

### Validation with PropTypes
Consider the following Message component.
```js
function Message({name}) {
    return <div className='message'>Hi, your name is {name}.</div>
}
```

Let's use this component in the following way.
```
<Message name="foo" />
<Message />
<Message name={2} />
```
This produces
```
// OK
Hi, your name is foo.

// Should ideally throw an error
Hi, your name is .

// Should ideally throw an error
Hi, your name is 2.
```

So, If we pass a number as a name prop or if we don't pass any prop, even then the text is rendered, but ideally, it should throw an error because `Hi, your name is .` doesn't make sense.

Luckily, React gives us a way to achieve this using PropTypes.

```js
const PropTypes = {
    string(props, propName, componentName) {
        if (typeof props[propName] !== 'string') {
            return new Error(`In component ${componentName}, ${propName} needs to be a string, but it was of type ${typeof props[propName]}`)
        }
    },
}

function Message({name}) {
    return <div className='message'>Hi, your name is {name}.</div>
}

// Component accepts an object as its `propTypes`. 
// Each key in that object is the name of each prop. 
// Each value is a function that takes (props, propName, componentName) 
//      as its arguments and returns an error if validation fails.
Message.propTypes = {
    name: PropTypes.string,
}
```

Now, whenever you try to pass anything other than a string to `name` prop, it will throw an error.

**Note:**
- PropTypes will be disabled by React in production environments for performance reasons.

### Using `prop-types` Package
Since cases like the above are so common, React team created a package called `prop-types` which will work in a similar manner. For example, if we want the `name` prop to be required and also a string, we can do so with the `prop-types` package in the following manner.

```
function Message({name}) {
    return <div className='message'>Hi, your name is {name}.</div>
}

Message.propTypes = {
    name: PropTypes.isRequired.string,
}
```

Check out [prop-types](https://github.com/facebook/prop-types) repo for more details.

### React Fragments
```html
<div id='root'></div>
```
Let's consider the following use case.
You have to add `<span>Hello</span>` and `<span>World</span>` to the `rootElement` using React.

In the end, the markup should look like
```html
<div id='root'>
    <span>Hello</span>
    <span>World</span>
</div>
```
Let's see if we can do this.
```js
const rootElement = document.getElementById('root')

const elementOne = React.createElement('span', null, 'Hello')
const elementTwo = React.createElement('span', null, 'World')

ReactDOM.render(?????, rootElement)
```
Now, what should be in the place of `?????` in the last line. It can neither be `elementOne` nor `elementTwo`, because we want both of them to be rendered (not one). But `ReactDOM.render()` takes only one react element as an argument and then appends it to rootElement.

One way to achieve this is if we can wrap both of the elements in a new element.

```js
const rootElement = document.getElementById('root')

const elementOne = React.createElement('span', null, 'Hello')
const elementTwo = React.createElement('span', null, 'World')

const combinedElement = React.createElement('div', null, elementOne, elementTwo)

ReactDOM.render(combinedElement, rootElement)
```

The above code may look fine, but it produces different HTML than what we needed.
```html
<div id='root'>
    <div>
        <span>Hello</span>
        <span>World</span>
    </div>
</div>
```

This is the reason why you can't do something like the following in your code.

```js
function Message() {
    return (
        <span>Hello</span>
        <span>World</span>
    )
}
```
Because there is no way for babel to be able to convert this to a single React.createElement()

React Fragments are introduced in `React v16.2.0` exactly to solve this problem. Now you can return multiple elements by just wrapping them around with `React.Fragment`.

For example,
```js
function Message() {
    return (
        <React.Fragment>
            <span>Hello</span>
            <span>World</span>
        </React.Fragment>
    )
}
```

React will ignore this `React.Fragment` when rendering.

So the previous problem can be solved now in the following way.

```js
const elementOne = React.createElement('span', null, 'Hello')
const elementTwo = React.createElement('span', null, 'World')

const combinedElement = React.createElement(React.Fragment, null, elementOne, elementTwo)

ReactDOM.render(combinedElement, rootElement)
```

**Note:**
- There is a shorthand representation for `React.Fragment`. 
    - Instead of writing `<React.Fragment>{childrent}</React.Fragment>`, you can write something like `<>{children}</>`. 
    - Both yield absolutely the same result.


### What did you learn?
In this article, you learned about 
- Creating custom components.
- The reason why the first letter of the custom component needs to be upper case.
- Validating the props of the custom component using `propTypes`
- Using `prop-types` package to validate props
- Rendering multiple elements at the same level using `React.Fragment`

### What's Next
In the next article, we will see how to style React elements. We will also see how to handle basic forms 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).

**Links and References:**
- [EpicReact.Dev](https://epicreact.dev) - Series of workshops with video explanations by [Kent C. Dodds](https://kentcdodds.com) based on which this blog post series is being written.
- [React Fundamentals Workshop Repo](https://github.com/kentcdodds/react-fundamentals) - Github Repo if you want to do the self-paced workshop yourself.
- [React Fundamentals Workshop Demo](http://react-fundamentals.netlify.app) - Production application of the above workshop repo.

---

You might also like the following articles that I wrote:
- [I Revamped GitHub Jobs Website Using Design From Frontend Mentor](https://blog.bhanuteja.dev/i-revamped-github-jobs-website-using-design-from-frontend-mentor)
- [React Fundamentals: Understanding JSX](https://blog.bhanuteja.dev/react-fundamentals-understanding-jsx)
- [React Fundamentals: Intro to React Raw APIs](https://blog.bhanuteja.dev/epic-react-react-fundamentals-part-1)
- [How I Gave A Modern Look For HackerNews Feed](https://blog.bhanuteja.dev/how-i-gave-a-modern-look-for-hackernews-feed)
- [Javascript You Need To Know For React](https://blog.bhanuteja.dev/epic-react-javascript-you-need-to-know-for-react)
- [My Review of Kent C. Dodds's EpicReact.Dev: Introduction](https://blog.bhanuteja.dev/epic-react-introduction)
- [React Fundamentals](https://blog.bhanuteja.dev/react-fundamentals)
- [Create Your Own Super Simple URL Shortener](https://blog.bhanuteja.dev/create-your-own-super-simple-url-shortener)
- [Why you should start using HSL color format](https://blog.bhanuteja.dev/why-you-should-start-using-hsl-color-format)
- [Embed Youtube Videos into Your Markdown Editor](https://blog.bhanuteja.dev/embed-youtube-videos-into-your-markdown-editor)
- [Babel Plugin To Remove Console Logs In Production](https://blog.bhanuteja.dev/babel-plugin-to-remove-console-logs-in-production)
- [Create Custom Markdown Parser](https://blog.bhanuteja.dev/create-custom-markdown-parser)
- [Add Typescript to your Next.js project](https://blog.bhanuteja.dev/add-typescript-to-your-nextjs-project)


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