[SOLVED] html Java javascript compiler software react Introduction to React

$25

File Name: html_Java_javascript_compiler_software_react_Introduction_to_React.zip
File Size: 621.72 KB

5/5 - (1 vote)

Introduction to React
React is a view creation library, built in JavaScript by the team at Facebook. If you have written websites using Express before, it is similar to Pug or EJS. React is designed to just handle the layout of your data it does not have any strong opinions on how that data is retrieved, stored, or manipulated, though here there are one or two caveats. Contrast this with a framework such as Angular, which expresses strong opinions on how your data flows through the application, how you perform HTTP requests, how your data is stored, and so on.
It is important to understand at the start that React is a view layer only. A presenter before anything else.
Getting Started
For the practicals, I recommend using CodeSandbox. It is a completely free, completely open source online editor for JavaScript in general. Using CodeSand- box means that you dont have to install any new software on your personal machines, dont have to handle differences between macOS, Linux and Windows
(a lot of packages on NPM, especially for front-end code, arent very friendly to Windows), and allow you to take your application with you to other machines by logging in with GitHub. We also know that everyone is working on the same platform, so it makes it much easier to debug issues with your tutor. It also lets you experiment freely with a disposable sandbox if you want to try something out, and you can fork your existing work if you want to try a new thing and not mess with your existing code. Whats more, you can export a .zip file from CodeSandbox with everything required to run your application somewhere else.
It uses create-react-app under the hood to create its React applications 1, which is the de facto standard for creating new React applications.
You can get a pre-prepared React application by going to this link, and can start hacking on it straight away with live reloading set up.
Ill add an appendix at the end for those who are eager to run things on their own machines (or for those interested) using create-react-app I wont be covering Webpack or similar. Consider that an exercise for the reader.
As you go through, youll see some Exercises. Make sure you try these out before moving on (where there will be solutions). You wont pick up much from this if you just copy the code I have written directly. I already know React, so you putting my code directly into your application without thinking about it first doesnt help you learn React.
Note: this guide will be making use of the latest ECMAScript standards (ES2015 and higher). This is assumed knowledge, but Ill try my best to explain things where necessary.
1CodeSandbox allows you to create a bunch of different applications online, so you can test out Vue, Angular or even Reason.
1

Note again: This prac expects a minimum of React 16.8.0 this is the latest version of React at the time of writing. Well be making use of hooks (for those that have used React before hooks greatly simplify a lot of things about React and make it easier for others to pick up).
Some Background JSX
JSX is the HTML-style syntax that React uses to declare elements. You can read a lot more about it here.
It is the building block for every React application. JSX is an extension to JavaScript (hence JavaScripteXtension) that allows for a much more familiar and natural syntax to be used. It is not, however, magic.
Take the following element:
const element =

Hello, World!

;
When rendered with ReactDOM, an almost identical element will appear in the
browser. However, the actual function call is:
const element = React.createElement(p, null, Hello, World!); You can see that the JSX is much more similar to the regular HTML you might
write, and is just some Syntactic Sugar over underlying function calls.
In practice, youll almost never need to use the createElement function directly.
It is, however, good to know what it is and how it works.
In this class, we do not have the time to cover it too deeply, but if youre curious about what a particular piece of JSX compiles to in JavaScript, you can look at the Babel REPL. Babel is the de facto compiler for JavaScript, and the REPL is an online compiler. You can paste (or type) your code in and see what the output of the compiler is.
Your First React App
I have created a starter kit here. The first thing youre going to want to do is fork the sandbox using the button in the top left of the page. If youre signed in to CodeSandbox, your changes will be associated with your account automatically. Otherwise, you can edit anonymously (but you cant keep your work hold on to the link tightly). If you want to work on it on your own computer (and youve got your computer set up for it) you can just download the starter directly from CodeSandbox and unzip it on your machine.
Youll be greeted by a simple React application lets break down all the pieces:
import React from react;
Even though React isnt explicitly used in the file, any time you see JSX being
used, you must import React into your application. CodeSandbox will remind 2

you if you forget.
import ReactDOM from react-dom;
React itself doesnt necessarily have anything special for the Web thats how projects such as React Native are possible. ReactDOM contains the special functionality to connect your React application to the DOM.
function App() { //
}
This is a React component. Yup. Its just a function that returns a valid Node you can think of this as being either some JSX, or null. Well cover whats
inside the component in a moment.
const rootElement = document.getElementById(root);
This, again, is not React-specific the document referenced there is the webpage itself. If you look inside public/index.html, youll see that there is a single div with an id of root. This is where we want our React application to mount
(attach itself).
ReactDOM.render(, rootElement);
Here is where we combine React with ReactDOM we render the App component, and tell ReactDOM to render it to the rootElement. This is the root of our React application everything else we render will come underneath this.
Alright! There is some content on the screen. Lets quickly go through whats inside App.
The first thing is a wrapping div. These are common in HTML, and in React. A div is used simply as a container to hold your other elements. It is important to note that a React component can only return one element at the top level (that element can have as many children as you like).

The above creates a div with a class of App in React, we dont use class because class is a reserved keyword in JavaScript. ReactDOM will take care of adding it correctly when it gets to the browser.
Inside the div, we have two elements, which are just standard HTML headings. Some things to note:
An element, in React nomenclature, is a DOM-native element, like div or p
A component is a custom element that you (or someone else) has created in React, like App above.
All elements start with a lowercase letter (as they would in HTML) All components must start with an Uppercase letter
3

Exercise: A simple one to get you started. Change some of the text inside the headings and check the result.
Adding Some Functionality
So, weve got our first application, but its pretty boring. Its just displaying static content, which is not the primary reason we use React.
Were going to add a Like and Dislike button, and keep track of the overall number of Likes.
The first thing we need to do is add the buttons and a place to display the count. Buttons are added straightforwardly via the button tag.
Exercise: Add 2 buttons one that says Like and one that says Dislike, and add a p that says Overall likes: 0. Update the h1 with a relevant title (you can get rid of the h2).
Answer:
It doesnt matter what else is in your App, but it should look something like this:
function App() { return (

Like Counter

Overall Count: 0


);
}
You can go ahead and click on these buttons. Nothing will happen. We need to add some state. State is the part of your application that remembers what has happened.
To add state, were going to be using Hooks these are a relatively new develop- ment in the React ecosystem, but they are part of the stable release and greatly simplify React overall. The previous way we did this was with Class Compo- nents which added a lot of overhead to the learning/understanding process. I recommend you read about them eventually, because a lot of companies will have code that uses them, but for now its enough to just know that Hooks arent the only way of doing this.
To use state, we need to import useState. This comes from the React package, and is a named export, so update you import line to look like this:
import React, { useState } from react;
Then, at the top of our App, we need to create the state.
4

function App() {
const [count, setCount] = useState(0);

Okay. Lets break down whats happening here. useState returns an Array with two elements the state, and a function that can be called to modify the state. We use Array Destructuring to give these items useful names. The argument to useState is the initial state. So, count is a variable that holds the number 0
(currently), and setCount is a function that can be used to update the count. This will keep track of the count over time, in between renders.
To display the count, we are going to update our p:

Overall Count: {count}

The curly-braces inside of the JSX are an instruction to tell JSX to return to regular JavaScript. That means that were going to use our new count variable. Saving your application, you should see no changes to your page, because the count is still 0. Lets make the count changeable.
A button has an onClick prop that we can use to help here. We can pass a function in that will allow us to change the count. For now, were just going to set it to something static.

What weve done here is added the onClick prop to the button, and passed in a function. The function calls setCount with a value of 10. If you save your page now, and press Like, you should see a change.
Exercise: Add an onClick to the Dislike button to set the count to -1
Notice, however, that when you click on the buttons it just updates the state to some completely new state. We need to use the old state to compute the new state.
To make our lives simpler, were going to create two functions, increment and decrement, that will add one and remove one from the count.
Inside of App, below your useState(0) call, add the following:
const increment = () => { setCount((oldCount) => oldCount + 1);
};
Note the use of lambda syntax the () => { }; defines a function, and we will use this frequently. And the code itself may be a little confusing weve just passed a function to setCount? Some of you may have been expecting increment to look like this:
const increment = () => { setCount(count + 1);
5

};
This might work, but is not safe. The reason for this is: React doesnt always update straight away. It sometimes combines a couple of updates and does them all at the same time. That means that if you pressed the Like button a bunch of times before the update applied, youd be adding to the old count every time, and would end up with only 1 more than you had before. When you pass a function to setCount, it will be called with the correct value of count for when the update is run.
Tl;dr: If you are using state to update your state, pass a function. Otherwise, pass the value.
Exercise: Write the decrement function.
Once you have both functions, update the onClick for the Like and Dislike
buttons:


And now, when you save, youll have a working application that keeps track of the values over time!
Exercise: Add a Super Like button that adds 10 to the count every time you press it. For bonus points, make sure it can only be pressed twice.
Reusable Components
Now that weve built a simple application, we should try and extend it. The goal for this section is for us to be able to have a bunch of headings, each with its own individual Like and Dislike buttons and counter.
The first thing we need to do is make a new React component for the like and dislike buttons. A component is a nice, simple unit of code that is essentially independent from anything else. We isolate components by making a new function and including the relevant pieces within that function body.
First things first, lets make our component. As mentioned earlier, a component is just a function that returns some React code. App was our first component, and now were going to make a second component called LikeCounter. To do this, create a new function above App that looks like this:
function LikeCounter() {
/* our code will go in here */
}
If you want to race on ahead, try and extract the relevant pieces out of App that make up the Like and Dislike buttons. Otherwise, follow along.
The first thing we need to do is take the words and the buttons. Keep in mind that we can only return one element from a component, so well need to wrap
6

our buttons and text in something. For now, well use a div, because it doesnt really change what anything looks like.
function LikeCounter() { return (

Like Count: {count}


);
}
Some things to note. First, Ive changed Overall Count to Like Count keep in mind that we want to show the number of likes per title. Secondly, note that we wrap the element weve returned in parentheses. This is technically optional, but is very good practice to avoid the problems that can arise from Automatic Semicolon Insertion. You dont need to think about it too much just remember to wrap your return statements in parentheses if they span multiple lines.
Now that we have our LikeCounter component, we can bring across the state. In this case, the state will reflect the individual count, and is used only in the one component nothing else needs to reference it, so we can bring it in to our new component with no problems.
function LikeCounter() {
const [count, setCount] = useState(0);
const increment = () => { setCount((oldCount) => oldCount + 1);
};
const decrement = () => {
setCount((oldCount) => oldCount 1); };
return (

Like Count: {count}


);
}
Now, inside of App, you can remove the state, the Overall Count text and the Like + Dislike buttons. Then, add in your LikeCounter as shown below. When you save, you should notice only a difference in the text everything should work in the same way as before.
7

function App() { return (

Like Counter

);
}
Cool! Now weve made our first reusable component! You can add as many LikeCounters as you like to the page, and theyll all work independently.
The next thing we need to do is make a component to hold our titles + like buttons. What were aiming for is something that looks like this:

Inside the component we will have an h1 that displays the title text, and the LikeCounter from above. Well have to figure out how to access the text weve passed in.
This is called a prop in React. A prop is something you pass into a React component. You can think about it almost like the parameter to a function
(because they are!).
Every React component you create has all its props passed to it as an object in the first argument. Take the following example:
function Test(props) {
console.log(props);
return null; // every component *must* return something
}
Now, in the following examples, props will be an object that contains whatever values you pass in:

// `props` is an object like this: { title: Hello }

// `props` is an object like this: { number: 5 }
console.log(hello!)} enabled={true} disabled={false} />
// `props` is an object like this: { fn: Function, enabled: true, disabled: false }
As you can see, you can pass any values you like as props. You can also see that for values other than String, you must wrap it in curly braces remember from above that the curly braces allow for regular JavaScript to be used inside JSX. The final thing you should know about props if you have a boolean prop, and you want to set its value to true, you can just add the name of the prop. For false, you must still pass in the value explicitly. See the following:
8


// `props` is an object like this: { enabled: true, disabled: false }
Here, enabled is set to true, because weve used the prop name there directly. However, for disabled to be marked as false, we must specify it.
Now, we probably have enough information to make our Headline component.
Exercise: Create the Headline component with the API from above. It should have an h1 that displays the title you pass in as a prop, and a LikeCounter. Try this yourself before looking below for the solution.
Answer:
function Headline(props) { return (

{props.title}

);
}
Now, you can use your Headline in App as many times as you like with a bunch of titles, and theyll all show up. You can like and dislike each of them individually.
Resources
If you want to get ahead of the pack, I highly recommend watching the (free) EggHead course The Beginners Guide to React by Kent C. Dodds.
It covers a lot of content, and is designed for beginners. Link here. The official React docs
9

Reviews

There are no reviews yet.

Only logged in customers who have purchased this product may leave a review.

Shopping Cart
[SOLVED] html Java javascript compiler software react Introduction to React
$25