Using React in CodePen.io

A very basic guide on how to set up things on CodePen.io to start working with React.

Introduction

This is a guide on how to set up CodePen.io to use React (useful for those in the freeCodeCamp certfication) and also how to make it as a template to use it everytime you want to use React in CodePen.io.

Note: there are other online tools that allow you to start off with a React project with no configuration needed so if you don't really need to use CodePen.io try using one of the alternatives. Some of them are:

  • CodeSandbox
  • StackBlitz
  • Replit

How to start

  1. Create new Pen: in order to start coding we need to create what is called a 'Pen', which opens up some editors (HTML, JSS, CSS).

  2. We know that React is a library, so we need to add this library to our Pen in order to start using it.

Adding React

First of all we need what is called a preprocessor . On settings, we will choose Babel since it includes JSX processing which is what we want to make our React code work. imagen.png

Just below we will add React as an external script or as a package. We will search for React and React-dom, this last one will provide us with the render method that we'll use to render our React code.

  • As script. Adding React by a CDN link to our HTML. imagen.png Note: These scripts doesn't actually show in the HTML editor since that editor only shows what's inside our <body> tag.

  • As a package, as you would do it with a package manager such as npm or yarn. imagen.png imagen.png This will add these import lines to our JS code: imagen.png

Coding in React

To start working with React we will add a 'root' element in our HTML editor:

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

Then we create a component in the JS editor, called App in this case:

const App = () => <h1>React starter</h1>

Just below we invoke the render method:

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

Note: With this line we are telling React that it should use the root element to render our App component.

And we can start working with React now.

Making it template.

By default CodePen provides us with some templates such as Vue or Flutter starters but React doesn't show as one. You can actually make this a template so next time you want to start coding in react you can start faster.

Go to settings and in the template section toggle "Make template?" on.
imagen.png

Next time you want to start a project choose create a project from template and your Pen will be ready to use with React. imagen.png

This is a very basic article, but I really hope it helps at least someone through their journey. Thanks for reading.