Creating a simple React component

Trey Alexander Davis
Byte-sized React
Published in
2 min readSep 5, 2017

Let the games begin…

Don’t know what React is? Check out this story.

Otherwise, let’s get up and running with CodePen. CodePen is a cloud-based development environment for front-end developers.

Sign up for CodePen for free here.

Now let’s create a new pen.

https://giphy.com/gifs/auaEStgx2lonS/fullscreen for HD

Next add Babel, React, and ReactDOM to the pen. The Babel preprocessor will convert our JSX into plain JavaScript. The React library will create our React components, and the ReactDOM library will render our components to the DOM.

https://giphy.com/gifs/s2aFAMRG9QAXS/fullscreen for HD

Let’s set up the index.html file. React does most of the HTML rendering, so all we need to do is insert a simple div element for React to append to (think of the HTML section in CodePen as being the <body> of the document, so no need to include a <head> element).

<div id="root">
</div>

We will be writing a functional React component, which is the most simple component in React. Let’s make a simple <h1> header, by adding the following code snippet to the ‘JS’ pane in CodePen:

const Hello = () => {
return <h1>Hello world!</h1>;
};

Let’s break this down. We declared a function that returns JSX. Babel converts JSX to plain JavaScript, so the function actually looks like this:

function Hello() {
return React.createElement(
'h1',
null,
'Hello world!'
);
}

The React.createElement function returns a virtual React component. Now that we’ve written our component, we need to tell React to render it to the DOM using the ReactDOM.render function. Add this code snippet to the ‘JS’ pane in CodePen:

ReactDOM.render(
<Hello />,
document.getElementById('root')
);

Babel converts the ‘<Hello />’ JSX into the previously declared Hello function that returns our virtual React component. The ReactDOM.render function appends the Hello component to the div we declared in the HTML file.

Now you should be seeing this in codePen:

Let’s take one more look at what is going on here:

You can check out the simple CodePen here:

https://codepen.io/trey-davis/pen/VzNyra

We are just getting the wheels rolling on this thing- next let’s nest some components.

--

--