JavaScript in React

Using JavaScript in React

React is a JavaScript library. You can create the following JavaScript expressions in your React projects:

  1. Variables
  2. Loops
  3. Functions
  4. Conditionals
  5. Objects
  6. Strings
  7. DOM and Window events.

The syntax is a little different in React, but the functionality is the same.

A Note on Naming Conventions.

In React part 1, we used className to apply CSS stylings instead of class. This is because class is a JavaScript keyword. React adapted by using className. Note the use of camelCase.

We can use the onclick method in React, but we need to apply camel casing to the name: onClick.

W3 Schools created some nice examples of React Events if you would like to learn more.

JavaScript Variables

We can render variables inside our components by encasing them in curly braces { }. The curly braces act as escape characters for JSX. They inform the JSX to render the element inside of the brackets.

Example: Variables
1
2
3
4
5
6
7
8
9
const name = "Willow"

function Hello(){
   return(
      <p>Hello! My name is {name}!</p>
   );
};

export default Hello;
Check the output

name was declared in line 1, as a JavaScript string. We can render it inside the Hello function by using curly braces. The curly braces let the JSX and HTML know that we want to use the variable name and its value. If we left off the curly braces, the word name would appear in the browser. The message would read “Hello! My name is name”.

Template literals

You can use template literals to work with strings. This can be easier than concatenation and more flexible than hard coding. These can be very useful with loops, conditionals, and lists.

Template Literal syntax:

  • Encase the entire template literal within { } since it is a JavaScript string
  • Enclose the entire string in backticks ``
  • Variables need to be inside curly braces {variableNameHere}
  • $ are escape tokens and introduce each variable within the template literal ${variableNameHere}

Should look something like this when you put it all together: {'Hello, ${variableNameHere}'}

Example: Template Literals
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
let num1 = 4;
let num2 = 7;
num2 = 8

function TemplateLiteral(){
   return(
      <div>
         {`(${num1} * ${num2}) is ${num1 * num2} and (${num1} + ${num2}) is ${num1 + num2}`}
      </div>
   );
};

export default TemplateLiteral;
Check the output

Arrow Functions

Arrow functions are simplified functions. You can use an arrow function as an argument for other functions. They do not affect the global scope of the project. Due to their scope, they can be very useful for defining props, loops, and conditionals. These functions will return values without using the return keyword.

Why not only use arrow functions? For long functions. They are great for short expressions but longer functions can be hard to read.

Example: Comparison of Functions
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
//comparing functions

function Greeting(){
  return( 
      <h1>Hello!  I am a standard function.</h1>   
   );
}

const ArrowGreeting = () => (
      <h1>Hello! I am an arrow function.</h1>
);
Check the output
Example: Combining Functions
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
//function with an arrow function

function ShinyButton(){
   const handleClick = () => {
      alert("You clicked me!");
   }
   return(
      <button onClick={handleClick}>
         Click This Button!
      </button>
   );
}

export default ShinyButton;

Working with Props and JS

Recall from the previous chapter , props are arguments passed to and between functions. We can use anything as a props, since props are placeholders.

We can use props to pass data between components.

Example: Props
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function GreetFriend(props) {
   return(
      <h1>Hello, {props.name}!</h1>
   );
}

function Greeting(){
   return(  
      <>
         <GreetFriend 
            name="Willow" 
         />
      </>
   );
}

export default Greeting;
Check the output

We can declare our props. This can make the code more meaningful and easier for humans to understand.

Example: Defined Props
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function GreetFriend(name) {
   return(
      <h1>Hello, {name}!</h1>
   );
}

function Greeting(){
   return(  
      <>
         <GreetFriend 
            name="Willow" 
         />
      </>
   );
}

export default Greeting;
Check the output

We can also set default variables for props.

Example: Default values
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
function GreetFriend(name ="Tacocat") {
   return(
      <h1>Hello, {name}!</h1>
   );
}

function Greeting(){
   return(  
      <>
         <GreetFriend 
            name="Willow" 
         />
         <GreetFriend />
      </>
   );
}
export default Greeting;
Check the output
Note

Lines 9 and 14 in the example above are empty tags. These are Fragments. Fragments allow you to group many elements and treat them as a single element. You will often find fragments in return statements.

Importing and Exporting

Exporting Components

There are multiple ways to export. We recommend you pick one way and remain consistent with it throughout your codebase. It will help with readability.

Example: Exporting

Option 1: After the function

1
2
3
4
5
6
7
function GreetFriend(name ="Tacocat") {
   return(
      <h1>Hello, {name}!</h1>
   );
}

export default GreetingFriend;

Option 2: As part of the declaration

1
2
3
4
5
export default function GreetFriend(name ="Tacocat") {
   return(
      <h1>Hello, {name}!</h1>
   );
}

Importing Components

You can import components to other components, not just App.js.
In the example above, GreetFriend and Greeting are in the same file. We could create separate files for them and import GreetFriend into Greeting.

Importing Other Things

You can import non-component portions of your codebase. JSON files are a commonly imported item.

Data is stored in a JSON file. We import to the component. The component is able to find the data. In this example, it is a name. GreetFriend imports the JSON file and then uses it to complete the greeting message.

Example: Working with JSON
1
2
3
4
// File is nameData.json
{
   "name": "Hermes"
}

When you import something that you plan to use in a function, be sure to give it a name if none exists. In this example, there is only a file name. We assigned it the name data. This data is an object, so we can use dot notation to access the object’s values with the keys.

1
2
3
4
5
6
7
import data from './nameData.json'

function GreetFriend() {
   return(
      <h1>Hello, {data.name}!</h1>
   );
}
Check the output

Check Your Understanding

Question

What structure is used to contain JavaScript variables?

  1. Brackets [ ]
  2. Parentheses ( )
  3. Double Quotes " "
  4. Curly Braces { }
Question
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const bookInfo = {
   title: "Dracula",
   author: "Bram Stoker",
   published: 1897 
}

function Book(){
   return(
      <p>My favorite book is {title}</p>
   );
};

export default Book;

Is returning the following error:

'title' is not defined  no-undef

Which syntax will correctly assign a value to title?

  1. <p>My favorite book is Dracula</p>
    
  2. <p>My favorite book is {bookInfo.title}</p>
    
  3. const BookInfo = () => {
       return(
          <p>My favorite book is {title}</p>
       );
    }
    
  4. function Book(props){
       return(
          <p>My favorite book is {props.title}</p>
       );
    };
    
Question

How would you rewrite the following arrow function as a regular function?

const SayHello = () => {
   
   return(
      <h1>Hello!</h1>
   );
}

export default SayHello;
  1.    function SayHello(){
             return(
             <h1>Hello!</h1>
          );
       }
    
  2.    function SayHello("Hello"){
             return();
       }
    
  3.    const SayHello(){
             return(
             <h1>Hello!</h1>
          );
       }
    
  4.    function SayHello(){
             return(
             <h1>{Hello!}</h1>
          );
       }