Purpose: To learn React, building from a minimal example to demonstrate basic features. Everything in this exercise can be run on the React Dev Server.
Create a new react project using the directions from Exercise 5.1. Don't forget the modifications from the "Modify to Run in a Subdirectory" subsection. To make a clean minimal project:
Optionally, you may want to create a shell script or batch file to do the above, to create minimal react projects easily. If you do, you will want to avoid the option to build and run immediately.
You may notice this line in the default index.html for Vite-React packages:
The HTML <link rel="icon"> tag affects the "fav icon," the tiny icon at the top of the web browser tab. Since the You can either eliminate this line or replace it with your own fav icon. If you want to create your own fav icon, you can use SVG, ICO, PNG, or most any other image / icon format. If you use a batch file or shell script to start a react project, you may want to set this up as well.
Start with a page with basic nav and footer, similar to the sample app way back in Exercise 1.1.
Notice the Empty Tag. You may notice the empty tag: <></>. When you use these HTML-looking tags, React turns them into a JSX object, which will ultimately be rendered as a component. The trouble is, you can return only one at a time. If you want to return two or more beside each other, wrap them in the empty tag: <></>.
Notice the XML Shorthand Closer. You may also notice that the hr tag, which usually has no closer, has an odd looking syntax: <hr />. In JSX, all tags must close. It is permissible to write <hr></> but not <hr> with no closing tag. <hr /> is an XML shorthand for <hr></>. These XML shorthand closers are used quite a lot in React code.
Test the Links. You will notice that the URL bar changes but they all go to the same place. Go to console mode and enter window.location. This Javascript global variable allows you to determine what the URL bar has in it and fake regular multi-page navigation. But Javascript has window.location. Discuss .href and .pathname attributes among others.
The first great thing about React is its ability to modularize HTML by dividing it into reusable components. Below is an example of multiple components in App.jsx:
Notice the Capitalization. React is strict that regular HTML tags must start with lowercase, while component tags must start with uppercase.
Compare to Other Modularization Methods: At the start of class, we used AJAX includes to modularize HTML. There was an awkwardness, a sort of backward feeling, because the include code had to run separately, after the DOM rendered. When we switched to server-side include, the feeling was more forward / sequential, like programmers expect. React runs completely client-side, like AJAX includes, but it retains the forward / sequential feeling of server-side includes. It does this because it starts from a blank div and renders everything inside it.
It helps to organize your code by splitting into files and importing. The same code as above is split into files, as follows:
Export and Import: Notice the "export default" keyword in Nav.jsx and Footer.jsx. The statement import Nav from './Nav' requires Nav to be the default export of Nav.jsx. If the keyword "export" is used without "default", then the import keyword imports an array of all exported items. Non-exported variables and functions are private to an imported module.
Comment on Directory Structure: Although we won't do it in this exercise, it is very easy to organize React into an arbitrary directory structure. The import functions work intuitively with directory structure. Much like our back end server code, React does much to free us from being tied to a file structure that matches URLs.
Much like Jinja templates, React allows us to include variables in a straightforward way (though with one set of curly braces, not two), as in the following example:
const location = "cave";
...
Change the Variable. You can now change "location" as suggested in the code above.
Notice the Use of Const. You may notice that the "const" keyword was used. There are many areas in React code where "const" is required, such as in state management. This is not one of those areas. An ordinary var would be fine here. However, it is considered a Javascript best practice to use const as often as one reasonably can, improving code predictability, readability, and helping prevent bugs.
Also like Jinja templates, React allows us to pass complex variables into templates like data structures and functions. The example below passes a JSON data structure into the Nav.
The most common way to iterate in React is to use the Javascript .map function, as in the Nav example below. What's really happening here is that .map takes an array and returns an array. An array of components displays just like components strung together with the empty tag <></>.
In this example, the links are squished together. The next example shows how to use add the | character to separate them.
Inside the .map loop:
This example uses the index i, adds | unless it is the first one.Inside the .map loop:
Put key={i} on the first child element of the .mapIt's now time to make it so the /about and /contact go to different pages, or at least appear to. The window.location.pathname global in Javascript helps us simulate URL routing even though everything goes through App.jsx. There are several ways to simulate routing in Javascript, but the example below uses conditional rendering, which React prefers instead of direct DOM manipulation. Conditional rendering can be done with an if statement, but not inside of a return statement, Inside of a return statement, the query operator is popular in React.
Image file: To make the contact route work, download batsignal.jpg and put it in the public directory. Both src="batsignal.jpg" and src="public/batsignal.jpg" should work for it. Also, if you ever need an absolute path to the public directory, there is a global variable called process.env.PUBLIC_URL that gives you that.
Notice the style attribute: You may notice that the style attribute in React uses a JSON object instead of a string. React requires this.
Better ways to do this: There is a more powerful way to simluate page routing in React (React Router) that we'll learn in the next exercises, but this will do for now.
It is common practice in React to put each page in its own component file that simulates HTML files.
In React, parent components can pass variables to child components in a uniquely HTML-looking way. React props look exactly like HTML attributes (see App.jsx below). Component functions take one argument: props, an object containing HTML-looking properties passed from parent component to child component (among other things). Take a moment to look at the two different versions of Home.jsx below, both of which are perfectly valid.
Change ...
To ...
Two syntaxes for receiving props: Although component functions take only one argument (props), you can use curly braces to raid that object for individual props. This is considered good form for making code maintainable, because it makes props visible and memorable. That said, it can be helpful to remind yourself from time to time that you are really just dealing with a single props object.
React props vs. HTML properties: Take note that React has no problem passing complex data as props, unlike HTML properties which are limited to strings.
The props object does more than just allow parent elements to pass variables to their child elements. The built-in props.children attribute allows React components to wrap and choose where to display what is wrapped, as shown below. Among other things, this feature makes inherited layouts work well, as shown below:
Now, bring in the responsive, accessible, professional features of Exercise 1.4.. First, in index.html, add bootstrap as follows:
Second, replace the current index.css with your css from that exercise, except replace the "body" tag with "#root" so that everything applies to the <div id="root"> in React.
Copy in the content of nav.html and footer.html from Exercise 1.4 into the component return statements in Nav.jsx and Footer.jsx, with the modification that "class=" should be replaced by "className=". Since all HTML in React is formed using Javascript, and the word "class" has an important meaning in Javascript, React requires a "className" prop instead of HTML's "class" attribute.
Finally, merge in the .map loop we used in the steps above into nav.html. The final resulting index.css, Nav.jsx, and Footer.jsx should look more or less as follows: