To be more specific, components are functions that tell React how to render one type of element. Each function takes a props object, and returns a new element that will be rendered in place of the original.
As an example, take this element with type XKCDComic:
let element =
React.createElement(XKCDComic,{
path:'compiling',
number:'303',
altText:"'Are you stealing those LCDs?' "+"'Yeah, but I'm doing it while my code compiles.'",})
The XKCDComic type is a function that takes some props, and maps them to an element that the browser actually knows how to render:
index.js
import React from 'react'
import ReactDOM from 'react-dom'
// XKCDComic React Component
// Steals Randall Munroe's work from xkcd.com
function XKCDComic(props) {
return (
<a href={`https://xkcd.com/${props.number}/`}>
<img
src={`https://imgs.xkcd.com/comics/${props.path}.png`}
title={props.altText}
/>
</a>
)
}
ReactDOM.render(
// Create an element of type XKCDComic, with the props `path`, `number` and
// `altText`.
<XKCDComic
path='compiling'
number='303'
altText={
"'Are you stealing those LCDs?' "+
"'Yeah, but I'm doing it while my code compiles.'"
}
/>,
document.getElementById('root')
)
Build In Progress
So what type of props can a component receive?
Like HTML elements, they can certainly receive strings and numbers. But custom components can also receive objects, arrays, functions — or even other elements!
Now that you know how to define components, it’s time to put your knowledge to work.
Remember the contact element that conditionally renders an image or the users initials? I’ve started you off with this below. I’ve also rendered a Contact element — which fails, because there’s no Contact function to tell React how to render `Contact elemtents.
Your task is to make the example work by creating the Contact function.
index.js
styles.css
import React from 'react'
import ReactDOM from 'react-dom'
import './styles.css'
// You'll need to convert this into a function component.
let name = 'James'
let names = contact.name.split(' ')
let initials = names.map(name => name[0].toUpperCase()).join('')
let element =
<div className='Contact' key={i}>
<div className='Contact-avatar'>
{initials}
<img src='' />
</div>
<span className='Contact-name'>
Hello
</span>
<a href="mailto:bob@example.com">
bob@example.com
</a>
</div>
ReactDOM.render(
<Contact
name='James'
email='james@frontarm.com'
photoURL='https://frontarm.com/courses/react-fundamentals/james-k-nelson.jpg'
/>,
document.getElementById('root')
)