Projects People Resources Semesters Blog About
React Basics (Setup, State, & Props)

React Basics (Setup, State, & Props)

Last Updated: 30 December, 2022

📊 Table of Contents

❓What’s React?

Today, it’s common to use a JavaScript framework to simplify creating re-usable building blocks and handling user interactions. A common framework developers use is called React.

React was developed at Facebook and released as open source in 2013. It’s easy to get started using it because React makes use of familiar HTML elements to output, has a huge community so it’s easy to get help, and is scalable so you can use it on applications both large and small.

💬 Past Presentations

Created in Fall 2022; presented by Allen Lin and Sam Phillipo
Created in Spring 2021; presented by Chris Myers

✳️ Getting Setup

  1. Make sure you have a recent version of Node.js and npm installed.
    • You can check your current version by running node -v and npm -v, respectively, in your terminal.
  2. In your terminal (Terminal on Mac, Command Line on Windows), navigate to your project folder using cd and enter: npx create-react-app my-app
    1. icon
      Terminal Basics:
      • Directory is another name for folder 📂
      • ls lets you list all the files in a directory
      • cd lets you change directory
    2. To use with TypeScript enter: npx create-react-app my-app --template typescript
  3. You can launch your project at any time by running npm start from within your project folder and navigating to localhost:3000 in your web browser. As you save changes to your React components, this page will update automatically. This is called hot reload.
    • You can shut down this development server any time by pressing Ctrl+c.

⌨️ JSX and TSX

React pages are written in JSX (or TSX) which are extensions of JavaScript (or TypeScript) that make it easier to write React code.

JavaScript, like Racket and Python, does not have static types, so many programmers prefer TypeScript as provides features which make programming more deliberate and convenient through type safety.

📦 The Power of Components!

React projects are structured into components, small building blocks which make up a larger project. (Your project is really just a big component.)

(Functional) Components all follow the same basic structure:

export function App() { // export your component
	// add any necessary functions here!

	return ( // return (render) some HTML/JSX content
		<div>
			<h2>Hello React.</h2>
			<p>Start editing to make things happen!</p>
		</div>
	);
}

Components allow you to abstract common elements in your code and allows you to break your complex project into smaller, more manageable/maintainable pieces.

As an example, if your header and paragraph in the above code were much more complex, you could break your App into two components with their own complex code:

// App.js
import Header from "./Header"; // import the Header component
import Paragraph from "./Paragraph"; // import the Paragraph component

export function App() {
	return (
		<div>
			<Header />
			<Paragraph />
		</div>
	);
}


// Header.js
export function Header() {
	return (
		<h2>Hello React.</h2>
	);
}


// Paragraph.js
export function Paragraph() {
	return (
		<p>Start editing to make things happen!</p>
	);
}

⚙️ Adding Functionality

What if you want to use variables and other functions with your code? This is where the power of React really shines over the classic HTML/JavaScript method. React makes it really easy to intersperse HTML and dynamic content!

// HeaderA.js
export function Header() {
	const name = "Allen"; // `const` defines a variable that will not change

	// use {} to place a JS block inside the HTML
	return (
		<h2>Hello {name}.</h2>
	);
}

🔄 State

React has one major limitation: it doesn’t know when to re-render (update) the screen as variables are changed. When should the function return again? You don’t want it to re-render every time any variable changes!

Instead, React developers make use of state. State variables are special variables which trigger a re-render of the view.

import { useState } from "react";

export function Counter() {
	const [gpa, setGPA] = useState(2);
	return (
		<div>
			<h2>Oasis average GPA: {gpa}</h2>
			<button
				onClick={ () => 
					setGPA(gpa + 1) 
				}
			>Increase GPA</button>
		</div>
	);
}

📩 Properties (aka Props)

Suppose we wanted the header (<h2> element) in the Counter to have a more complex output. We’d need some way of telling the header what number to display. This is where Properties, often shortened to Props, come into play.

Props let you make components more reusable since you can change what information they display. This is useful as variables change and across when re-using existing components where you need the same logic in more than one place.

// Counter.js
import { useState } from "react";

export function Counter() {
	const [gpa, setGPA] = useState(2);

	// set the value of the property `gpa` using `gpa={}`
	return (
		<div>
			<Header gpa={gpa}/>
			<button
				onClick={ () => 
					setGPA(gpa + 1) 
				}
			>Increase GPA</button>
		</div>
	);
}


// Header.js
import { useState } from "react";

export function Header({ gpa }) {
  // set up `Header` to accept
  // one property named `gpa`

	return (
		<h2>Oasis average GPA: {gpa}</h2>
	)
}

Additional properties can be added by separating them with commas. For example:

export function Header({ gpa, semester, studentName }) {
  // set up `Header` to accept three properties:
  // `gpa`, `semester`, and `studentName`

	return (
		<h2>
      Oasis average GPA for {studentName}
      during the {semester} semester: {gpa}
    </h2>
	)
}

📂 Actions on Load

Often you want to perform an action when a page is loaded. This may be fetching information from local cache or from a backend API. React provides a useful useEffect function which is run on load to perform an action when that component is rendered.

And here is a small example:

// Axios is a library for making HTTP requests (eg: GET, POST, PUT, DELETE).
// Learn more here: https://github.com/axios/axios

function MyComponent() {
	useEffect(() => {
		axios
			.get("https://apiurl.com") // GET data from this link
			.then(response => { // do this if successful
				// action if get is sucessful
			})
			.catch(error => { // do this if there's an error
				// action if there's an error
			})
	})

	return(
		<div>
			{/* Display the data in some way */}
		</div>
	);
}

🌐 Quick Note on API Calls

API calls tend to follow this structure:

image
  1. Frontend makes an API call to get data from a database or other server. Data is stored on the server in a format efficient for the server.
  2. Server responds to the API and sends back data in JSON format.
  3. The frontend has a previously defined Promise of the format of the data. It tries to unpack the data using this understanding.

🎨 A Pop of Color

Styling React is very similar to styling standard HTML. CSS works as before and the same concepts apply. That said, React (well, JSX) also has some convenience features to make it even easier to style without having to open a separate styles file! W3Schools has a great summary: