Preparing the development environment for React
Create React App
There is a very useful package called
create-react-app which will automatically install all your required dependencies, and set up a directory for your react app automatically.
Using Create React App
- Install Create React App globally
npm install -g creat-react-app
- From the command line type
npx create-react-app app-name
This will create a directory for the front end of your app called
app-name. Inside that there will be a package.json file with all the scripts you need to create a react app, run it locally, and build a production version of that site.
There are two main parts of the
If you create a production build with
npm run buildyou will additionally have a
buildfolder. More on that when we talk about serving React projects next week!
Core Concept: the
src folder is where the meat of your React project lives
- Create a JS file for each component
- Import components where needed
App.jsfile lays out the whole page
index.jsdraws the content to the page
- CSS for your project also goes in here
Core Concept: the
public folder is where your react component gets drawn to.
- Displays the front end of the app
- Keep images you want to display in here
- Don't tweak the HTML!
Lab: Create a React Component
Let's create our first React Component! If you haven't already installed
create-react-app go ahead and do that now
npm install -g create-react-app
cdinto your code folder
- create a React app named
- Change your app so it displays an
h1with the text "Hello, React!"
Note: After you open VSCode it will ask if you want to use eslint from node modules. React has it's own eslint extension to properly highlight react components so use it.
Core Concept: Class Based Components
As of React 16.8, and the introduction of Hooks class based components are starting to become less, and less common however it's still important to understand them as they reveal more of the internal processes of React, and are still fairly prevelant in older code.
The State Object
Every React component keeps track of its own state in an internal object named
state. In a class based component you can access state through
this.state. In a functional component you have to use Hooks to access state.
React likes to be in complete control of the page so it's important to only update the page through state, and never through direct DOM manipulation!
Class based components also have access to a component's lifecycle methods. These are methods which get called at certain points during the component's life.
The most common of these are:
componentDidMountfires when the component is first loaded onto the page
componentWillUnmountfires right before the component is removed from the page