React Training
React training cover picture

React Training

I did a training course???? on React?? these last three days, here are my notes??.


No alt text provided for this image
Day one of React course

JS Reminder

var vs let

with var in if :

var name ="outside";
console.log('before:'+name);


if(true){
? ? var name="inside"
? ? console.log('in the block:'+name)
}


console.log('after:'+name)


//outputs
// before:outside
// in the block:inside
// after:inside        

with let in if :

var name ="outside";
console.log('before:'+name);


if(true){
? ? let name="inside"
? ? console.log('in the block:'+name)
}


console.log('after:'+name)


//outputs
// before:outside
// in the block:inside
// after:outside        

concatenation

With '+'


let city='Lille';
console.log('I live in '+city);        

Better inverted quotes with dollar curly braces


let city='Lille'
console.log(`I live in ${city}`);;        

Functions

Anonymous function:

Arrow function:

Object

Careful with arrow fn in object/anonymous fn->loss of context

Use an upper method like timeout to bring context to arrow fn

Object destructuring

Spread operator

arrays

classes

modules

TypeScript

Sass

React before

with createElement

with JSX

React presentation

Definition

React is a JavaScript library for building user interfaces. It was developed by Facebook, and is often used for building single-page applications and mobile applications.

React allows developers to create reusable UI components. It focuses on the declarative approach to programming, which means that instead of describing the steps required to update the UI, you describe the desired state of the UI. React then takes care of updating the UI to match the desired state.

Companies using it

React is a popular choice for building user interfaces for web and mobile applications, and it has been adopted by many well-known companies. Some examples of companies that use React include:

  • Facebook: React was developed by Facebook, and it is used extensively within the company for building web and mobile applications.
  • Airbnb: The popular vacation rental website uses React for its user interface.
  • Netflix: The streaming service uses React for its web-based user interface.
  • Dropbox: The file hosting service uses React for its web-based user interface.
  • Asana: The project management software uses React for its web-based user interface.
  • Uber: The ride-hailing service uses React for its web-based user interface.
  • Pinterest: The social media platform uses React for its web-based user interface.
  • Microsoft: The technology giant uses React for several of its web-based applications.

These are just a few examples of the many companies that use React. It has become a widely adopted tool for building user interfaces, and it is likely that you will find React being used in many other well-known companies as well.

Virtual DOM (reconciliation)

Tools

Visual Code with ESLint (AirBnB), Prettier, Auto Rename tag

Browser: React developer tools

NodeJS (nvm to change of node version)


Practice 1

App creation with typeScript template


npx create-react-app my-app --template typescript        

Use of bootstrap, scss

https://react-bootstrap.github.io/components/table/

&

https://react-bootstrap.netlify.app/components/navbar/#rb-docs-content

First component creation

Creation of function and class components

Using of props

Lifecycle hooks in class component

UseEffect hook

Github repo at the end of first day



No alt text provided for this image
Second React training day


Practice 2

Lift up state

In the context of React, "lifting state up" refers to a pattern for managing state in a way that allows it to be shared between multiple components in a tree of components.

In React, components can have their own internal state, which is private to that component and can only be modified by the component itself. However, sometimes a component needs to share its state with other components in its tree. One way to do this is to pass the state down the tree as props, but this can become unwieldy if the state needs to be passed down multiple levels.

To address this issue, the "lifting state up" pattern involves moving the shared state to a common ancestor component, which can then pass the state down to its children as props. This allows the shared state to be managed in a single location, rather than being passed around multiple levels of the component tree.

Here's an example of how this might work:


class App extends React.Component 
? // App component is the common ancestor for the two child components
? // It has a state variable called "count" that it passes down as props
? state = { count: 0 }
??
? incrementCount = () => {
? ? this.setState({ count: this.state.count + 1 })
? }


? render() {
? ? return (
? ? ? <div>
? ? ? ? <ChildA count={this.state.count} incrementCount={this.incrementCount} />
? ? ? ? <ChildB count={this.state.count} incrementCount={this.incrementCount} />
? ? ? </div>
? ? )
? }
}


class ChildA extends React.Component {
? // ChildA component receives the "count" and "incrementCount" props from its parent
? render() {
? ? return (
? ? ? <button onClick={this.props.incrementCount}>
? ? ? ? Increment count: {this.props.count}
? ? ? </button>
? ? )
? }
}


class ChildB extends React.Component {
? // ChildB component also receives the "count" and "incrementCount" props from its parent
? render() {
? ? return (
? ? ? <div>
? ? ? ? Current count: {this.props.count}
? ? ? </div>
? ? )
? }
}

{        

In this example, the App component is the common ancestor for ChildA and ChildB. It has a state variable called count that it passes down as props to both child components. The child components can then access the count and incrementCount props and use them to render their respective UI and update the shared state.

json-server

Get a full fake REST API with zero coding in less than 30 seconds.

axios

Learn how to send and receive HTTP request with axios in React application.

CRUD: Create Read Update Delete

Enum


enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT",
}        

ErrorBoundaries

Context

Context lets sharing data between components.


// ---------------- Parent.js?
import {createContext , useState} from "react";


let contextName = createContext( )?
// you can optionally pass it a default value?
// it returns a "provider" object?


let Parent = () => {
? ? let [count , setCount] = useState()? ??


? ? return (?
? ? ? ? <div>?
? ? ? ? ? ? <contextName.Provider value={ {count , setCount } } >
? ? ? ? ? ? ? ? <Child/>
? ? ? ? ? ? </contextName.Provider>?
? ? ? ? </div>
? ? )
}


export {contextName};
export default Parent;




// file that consumes the context?
// --------- Child.js -----------


import {useContext} from "react";? ?
import {contextName } from "./Parent";


let Child = () => {
? ? let value = useContext(contextName);
? ? return (
? ? ? ? <div> {value} </div>
? ? )
}        

Github repository after day 2




No alt text provided for this image
The third day of React training

Practice day 3

Slot

In React, a "slot" is a way to compose components and reuse components in a declarative way. It allows you to specify where content should be placed in a component, similar to how you might use placeholders in a template.

Here is an example of how you might use slots in a React component:



import React from 'react';


function MyComponent(props) {
? return (
? ? <div>
? ? ? <header>{props.header}</header>
? ? ? <main>{props.children}</main>
? ? ? <footer>{props.footer}</footer>
? ? </div>
? );
}


function App() {
? return (
? ? <MyComponent header={<h1>My Header</h1>} footer={<p>My Footer</p>}>
? ? ? <p>Content goes here</p>
? ? </MyComponent>
? );
}        

In this example, MyComponent is a reusable component that has three slots: a header slot, a main slot, and a footer slot. When you use the MyComponent component in the App component, you can specify what content goes in each of these slots by passing in the content as props.

In the example above, the header slot is filled with an h1 element, the main slot is filled with a p element that is passed as the children prop, and the footer slot is filled with a p element.

Slots are a useful way to create reusable components that are flexible and customizable, and they can help you create more complex layouts and designs in your React applications.

Context Reminder

In React, context is a way to pass data through the component tree without having to pass props down manually at every level. It allows you to share values such as a theme or a user language preference between components, without the need to explicitly pass the value through each level of the component tree.

To create a context in React, you can use the createContext function from the react package. This function returns an object with a Provider component and a Consumer component. The Provider component is used to provide the value for the context, and the Consumer component is used to consume the value from the context.

Here is an example of how you might create and use a context in React:


import React from 'react';


const ThemeContext = React.createContext('light');


function App() {
? return (
? ? <ThemeContext.Provider value="dark">
? ? ? <MyComponent />
? ? </ThemeContext.Provider>
? );
}


function MyComponent() {
? return (
? ? <ThemeContext.Consumer>
? ? ? {theme => (
? ? ? ? <div className={`theme-${theme}`}>
? ? ? ? ? {/* component content goes here */}
? ? ? ? </div>
? ? ? )}
? ? </ThemeContext.Consumer>
? );
}

        

In this example, the App component is the provider for the ThemeContext context, and the MyComponent component is the consumer. The App component sets the value for the context to "dark", and the MyComponent component consumes the value from the context and uses it to set the className of a div element.

Using context can help you avoid prop drilling, which is the process of passing props down through multiple levels of the component tree. Instead, you can set the value for the context at the root of the component tree, and any component in the tree can consume the value from the context without having to explicitly pass it down.

It is important to note that context should be used sparingly, as it can make your code more difficult to understand and debug. It is usually better to pass data down through props if possible. Context should only be used when the value you need to share is not within the scope of a particular component and is needed by many components within the tree.

Reminder on useEffect hook

Tging side effects in function components, and it can be used to perform a wide variety of tasks. It is important to note that effects should be kept simple and should not contain any logic that modifies the component's state, as this can lead to unexpected behavior. Instead, state should be modified using the useState hook or by passing values down through props.

Decorator order explanation

The decorator pattern is a design pattern in software engineering that allows you to extend the functionality of an object dynamically, without changing the object's code. It is a flexible alternative to subclassing, and it allows you to add new behavior to an object at runtime.

In React, the decorator pattern can be implemented using higher-order components (HOCs). A higher-order component is a function that takes a component as an argument and returns a new component that wraps the original component and adds additional functionality to it.

Here is an example of how you might use the decorator pattern to add a new behavior to a component in React:



import React from 'react';


function withLoading(Component) {
? return function WithLoading(props) {
? ? if (props.isLoading) {
? ? ? return <p>Loading...</p>;
? ? }
? ? return <Component {...props} />;
? };
}


function MyComponent(props) {
? return (
? ? <div>
? ? ? {/* component content goes here */}
? ? </div>
? );
}


const MyComponentWithLoading = withLoading(MyComponent);


function App() {
? return (
? ? <MyComponentWithLoading isLoading={true} />
? );
}        

In this example, the withLoading function is a higher-order component that adds a loading indicator to the MyComponent component. The withLoading function takes the MyComponent component as an argument and returns a new component that wraps the original component and displays a loading message if the isLoading prop is true.

The decorator pattern can be useful for adding additional functionality to components in a flexible and modular way. It allows you to keep your components simple and focused on their core responsibilities, while still being able to extend their functionality as needed.

Some public API

https://github.com/public-apis/public-apis (use: Frankfurter, Open Food Facts, CitySDK )

https://geo.api.gouv.Fr

Cucumber integration test overview

Cucumber is a tool for behavior-driven development (BDD) that allows you to write acceptance tests for your application in a simple, human-readable language. It is often used to test web applications, and it can be used in combination with a variety of programming languages and frameworks, including React.

To use Cucumber with React, you will need to set up a test environment that includes Cucumber and a testing framework that can be used to test React components, such as Jest or Mocha. You will also need to write Cucumber feature files that define the acceptance tests for your application, and you will need to write step definitions that translate the steps in the feature files into executable code.

Here is an example of a Cucumber feature file for a simple React application:

Feature: Add todo ite
? As a user
? I want to add a todo item to the list
? So that I can keep track of my tasks


? Scenario: Add todo item
? ? Given I am on the todo page
? ? When I enter "Buy milk" into the input field
? ? And I click the "Add" button
? ? Then I should see "Buy milk" in the todo list

        

To implement this feature, you will need to write step definitions that define how to interpret the steps in the feature file. For example, you might write a step definition that looks like this:


Given('I am on the todo page', () => 
? // navigate to the todo page
});


When('I enter {string} into the input field', (todoItem) => {
? // enter the todo item into the input field
});


And('I click the {string} button', (buttonText) => {
? // click the button with the specified text
});


Then('I should see {string} in the todo list', (todoItem) => {
? // assert that the todo item is present in the todo list
});

{        

Once you have written your step definitions, you can use Cucumber to execute the acceptance tests and verify that your application behaves as expected. Cucumber provides a number of tools and libraries that can help you integrate it with your React application, and it can be a useful tool for testing the behavior of your application and ensuring that it meets the requirements of your users.

Redux


npm install @reduxjs/toolkit react-redux        

Unit test with Jest

Writing unit tests in React involves using a testing library to run assertions against your React components. One popular testing library for React is Jest, which is included as part of the create-react-app tool and can be used to test React components as well as other JavaScript code.

To write a unit test for a React component using Jest, you will need to do the following:

  1. Import the React and { shallow } objects from the react-test-renderer/shallow package. The shallow object allows you to render a component "shallowly", meaning it will not render any of the components that are nested within it. This is useful for isolating the component you are testing and avoiding unintended side effects.
  2. Import the component that you want to test.
  3. Write a test function that uses the shallow object to render the component, and then makes assertions about the component's output. For example, you might use the toMatchSnapshot method to check that the component's output is what you expect it to be.

Here's an example of a unit test for a simple Hello component that displays a message:

React Native

React Native is a framework for building native mobile applications using JavaScript and the React framework. It allows you to use the same codebase to build apps for multiple platforms, including iOS and Android.

With React Native, you can build mobile apps that are indistinguishable from apps built using native languages like Java or Swift. You can use the same design patterns, APIs, and tools that you would use to build a native app, but with the added benefits of using a declarative, component-based approach to building your user interface.

React Native is an open-source project, maintained by Facebook and a community of developers. It is widely used by companies and developers around the world to build high-quality, performant mobile apps.


Progressive Web App

A progressive web app (PWA) is a type of web application that aims to provide a user experience similar to that of a native mobile application, using modern web technologies. PWAs are designed to work on any device, regardless of the platform or browser, and can be installed on a device's home screen without the need for app store approval.

PWAs use modern web technologies such as service workers and web manifest files to provide offline support and app-like functionality, including the ability to receive push notifications and access device hardware. They are built using standard web technologies such as HTML, CSS, and JavaScript, and are delivered through the web, making them easily discoverable and accessible via a URL.

Some key features of PWAs include:

  • Offline support: PWAs can work offline or on low-quality networks, thanks to the use of service workers to cache content and manage network requests.
  • Add to home screen: PWAs can be installed on a device's home screen, just like a native app, making them easy to access and use.
  • App-like experience: PWAs can provide an app-like experience, with features such as push notifications, full-screen display, and access to device hardware.
  • Cross-platform compatibility: PWAs are designed to work on any device, regardless of the platform or browser, making them a convenient choice for developers looking to reach a wide audience.
  • Easy discovery and access: PWAs are delivered through the web, making them easily discoverable and accessible via a URL.

GitHub repository day 3

要查看或添加评论,请登录

Vincent Vauban的更多文章

  • ?? Broken Function Level Authorization – API5:2023 ??

    ?? Broken Function Level Authorization – API5:2023 ??

    I'm kicking off a series of articles on API Security ?? to help us—developers ????????—better understand and implement…

  • [VV112] The Java 21 Newsletter

    [VV112] The Java 21 Newsletter

    ????2??1?? Dear followers, let's prepare for Java 21 certification together! 1?? How would you answer this question:…

  • FR Les mots sans les maux. ???

    FR Les mots sans les maux. ???

    FR Hier, j’ai eu la chance d’assister à un atelier sur la Communication Non Violente (CNV) avec les superbes people de…

  • ?? Unrestricted Resource Consumption – API4:2023 ??

    ?? Unrestricted Resource Consumption – API4:2023 ??

    I'm kicking off a series of articles on API Security ?? to help us—developers ????????—better understand and implement…

  • ?? Broken Object Property Level Authorization – API3:2023 ??

    ?? Broken Object Property Level Authorization – API3:2023 ??

    I'm kicking off a series of articles on API Security ?? to help us—developers ????????—better understand and implement…

  • [VV111] The Java 21 Newsletter

    [VV111] The Java 21 Newsletter

    ????2??1?? Dear followers, let's prepare for Java 21 certification together! 1?? How would you answer this question:…

    18 条评论
  • ?? Broken Authentication – API2:2023 ??

    ?? Broken Authentication – API2:2023 ??

    I'm kicking off a series of articles on API Security ?? to help us—developers ????????—better understand and implement…

  • ?? BOLA – The #1 API Security Threat (API1:2023)

    ?? BOLA – The #1 API Security Threat (API1:2023)

    I'm kicking off a series of articles on API Security ?? to help us—developers ??????????—better understand and…

  • [VV110] The Java 21 Newsletter

    [VV110] The Java 21 Newsletter

    ????2??1?? Dear followers, let's prepare for Java 21 certification together! 1?? How would you answer this question:…

  • ?2??4?? Java 24 features with Thiago

    ?2??4?? Java 24 features with Thiago

    (Thanks Thiago Gonzaga ) Here are some insights based on Thiago X content. Java 24: JEP 491 Boosts Virtual Threads! ??…

社区洞察

其他会员也浏览了