How to use React outside of CodePen

I’m just learning React and so far I love it. It’s amazing to have more structured HTML code that can use Javascript! Through freeCodeCamp I was used to writing in JSX. On CodePen, I continued doing the same. To use JSX on CodePen, you flick the switch in settings to enable Babel in the JS window. So simple!
However what about in the “real” world? I started moving some projects off CodePen and onto GitHub (you can read how to do that here), and realised I had no idea how to render JSX on my own. During the export, CodePen converted JSX to JS for me. This was great, but meant that I had no idea how to write new code or refactor my old code.
Here are the steps I used to keep writing in JSX outside of CodePen. It is from the ReactJS website, but for whatever reason, it took hours of Googling to find this one page and understand what it was doing.
1. Create a `src` folder
Navigate to the project folder. Create a folder inside your project called src
. This is where you should put your JSX file. You can call the file anything you’d like, just make sure it ends in .jsx
or .js
. I use .jsx
so it’s really clear what it is.
2. Install the JSX preprocessor
To convert the JSX file into JS, we need a JSX preprocessor. We are using Babel. Babel takes new JS language, such as arrow functions and JSX, and converts it into “traditional” JavaScript. Your computer only understands “traditional” JavaScript, which is why it won’t run JSX on its own.
To install Babel, navigate to the project folder in terminal and type in the following code. You need to do this for every project.
npm init -y
npm install babel-cli@6 babel-preset-react-app@3
3. Run the JSX preprocessor
Now we have Babel installed, we need to actually run it. When we run it, Babel will look at your .jsx
file inside the src
folder. Each time src\script.jsx
is updated, the preprocessor will convert the JSX into JS, and update script.js
in the main folder. Point your HTML file to use the script.js
file in the main folder (not the src
folder). That’s the end!
To run Babel, navigate to the project folder in terminal and type in the following code:
npx babel --watch src --out-dir . --presets react-app/prod
This sets the terminal up to do the conversion. As long as this is running, you can keep making changes and the conversions will keep happening. If you want to stop Babel, press control + c.
Every time you want to make a change to your JSX file, this command must be running in the background.
So if you exit terminal, come back in a few hours and want to work on your site again, make sure you remember to run the npx
code once more.
Well done, you should be up and running now!
Not sure how to put your code online without the help of something like CodePen? Take a look at my other tutorial: How to move from CodePen to GitHub.