React Components are custom types

Custom types

If there’s one that thing you should take away from this course, it’s that React.createElement() returns plain old JavaScript objects with a type and some props.

// Elements are just objects, and they look something like this:
{
  type: 'a',
  props: {
    children: "James",
    href: "mailto:james@frontarm.com",
  }
}

As you’ve seen, elements are often used to describe a chunk of HTML that needs to be rendered. This means that elements are great for representing documents - you can describe paragraphs with type 'p', list items with type 'li', and headings with type 'h1'.

But what if your app calls for more complicated types?

#Components

Imagine that you’re building an app to track your frequent dealings with billionaires, and you’d like to re-use the same “Contact” component in multiple places.

With HTML, each time that you want to render the component, you’d need to create the same complicated group of elements, with the same specific types and props.

With React, you just create a Contact type, and use it as you’d use any other type.

index.js
Contact.js
styles.css
import React from 'react'
import ReactDOM from 'react-dom'
import './styles.css'
import { Contact } from './Contact.js'

let element = React.createElement(
  // Custom types can be used in place of HTML element names
  Contact,

  // Custom types can accept any props they need
  {
    name: "James K Nelson",
    email: "james@frontarm.com",
  },
)

ReactDOM.render(
  element,
  document.getElementById('root')
)
Build In Progress

In the React parlance, these custom types are called Components.

To create a component element, you follow exactly the same process as for HTML elements. You just pass a type and some props to React.createElement(). You still get an element object in return. And you can still pass that element object to ReactDOM.render().

But what happens when you render a Component element?

While the browser is an expert on HTML types like 'div' and 'p', it doesn’t know the first thing about app-specific types like Contact. And that’s why you’ll need to teach it!

Progress to next section.