Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 23, 2021 12:41 pm GMT

Learn React & Higher Order Components (HOCs) By Building Netflix

learn-react-by-building-netflix

Click if you like the project. Pull Requests are highly appreciated

Github link: https://github.com/hieptl/netflix-clone/tree/main/advanced/netflix-hoc#what

I'm Hiep. I work as a full-time software engineer. Most of my open-source projects are focused on one thing - to help people learn .

The repository helps you learn higher order components (hocs) by building Netflix. It means that you are learning higher order components by building a real-life project. I will explain concepts in details. This post is the third part in my series and it is suitable for beginners.

If you feel the repository is useful, please help me share the post and give me a Github . It will make me feel motivation to work even harder. I will try to make many open sources and share to the community.

Preface

This course will help you to learn higher order components (hocs) by building Netflix. It means that you are learning by doing a real-life project.

Table of Contents

Table of Images.

0. How to Run the Project.

  • Step 1: Clone the project by using git clone or download the zip file.

  • Step 2: Open "terminal" / "cmd" / "gitbash" and change directory to "netflix-clone" and run "npm install" to install dependencies.

  • Step 3: Run "npm start" to run the fron-end project.

1. Live Demo.

2. Introduction about the Creator.

2.1. Greenwich University.

  • GPA 4.0 / 4.0.

  • Machine Learning paper - Recommendation System - IEEE/ICACT2020.

  • Co-Founder / Mentor IT club.

2.2. Hitachi Vantara Vietnam.

  • Employee of the year.

  • Second prize - innovation contest.

  • Techlead - HN branch.

  • One of CoE Leaders (Center of Excellence).

3. Prequisites.

3.1. Softwares.

  • Install NodeJS.

  • An IDE or a text editor (VSCode, Intellij, Webstorm, etc).

3.2. Technical Skills.

3.3. Materials.

  • Html, css, js (source code) was prepared because I want to focus on React and share knowledge about React. Building html and css from scratch would take a lot of time.

  • README.md (the md file will contain everything about the course).

  • Netflix data will be used to import to Firebase. In this course, we use Firebase as our back-end service.

4. Purposes of the Course.

4.1. Final Project.

  • The course would help you have understanding about React and higher order components.

  • You could build the final project with end-to-end solution (front-end solution using React and back-end solution using Firebase).

4.2. Job.

  • After finishing the course, you could get a job with fresher / junior position.

5. Higher Order Components.

5.1 What.

  • Higher-order function is a function that accepts another function as an argument or returns a function as a return value or both.
const firstOrderFunc = () => console.log ('Hello, I am a First order function');const higherOrder = ReturnFirstOrderFunc => ReturnFirstOrderFunc();higherOrder(firstOrderFunc);
  • A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from Reacts compositional nature.

  • A higher-order component (HOC) is a function that takes a component and returns a new component. Basically, it's a pattern that is derived from React's compositional nature.

  • We call them pure components because they can accept any dynamically provided child component but they won't modify or copy any behavior from their input components.

const EnhancedComponent = higherOrderComponent(WrappedComponent)

5.2 Why.

HOC can be used for many use cases:

  • Code reuse, logic and bootstrap abstraction.

  • Render hijacking.

  • State abstraction and manipulation.

  • Props manipulation.

5.3 How.

  • Step 1: Create a function that accept a component as parameter.

  • Step 2: Add common logic that can be shared between components inside that function.

  • Step 3: Pass the custom logic to the input component via props.

  • Step 4: Export the created function.

  • Step 5: Import the created function into any components that need to use it.

  • Step 6: Wrap the component by using the imported function and then export it.

For example:

export default withHOC(YourComponent);

5.4 When.

  • We can use higher order components if we want to reuse logic and share code between components.

  • By the way of illustration, we need to display a modal in different places. The code of showing / hiding the modal need to be shared between components instead of creating new functions for different components.

  • We can have several solutions to achieve the result such as using Redux, React Context API, ... to keep track the state of the modal. However, we will use higher order component to achieve the same result. For this reason, you can understand higher order component by applying to our Netflix.

7. Apply Higher Order Components to Netflix.


apply-higher-order-components-to-netflix

Figure 1. Apply Higher Order Components to Netflix.

We will understand about higher order component by applying to our Netflix. In the first past of the series, we did not validate the user's credentials. In this part, we will validate the user's information and show the warning dialog if the user's information is invalid.

Step 1: Create Modal.js file inside src/components/Modal folder. This file is used to define higher order component.

function withModal(WrapperComponent) {  return function () {    const showModal = ({ message }) => {      window.alert(message);    };    return <WrapperComponent showModal={showModal} />;  };}export default withModal;

1st NOTE:

  • We can user higher order component pattern to share code between components. In this case, we need to show the modal in different places. For this reason, we will create a higher order component which is call withModal to show the modal.

  • the showModal function will accept an json object as parameter. The json object will contain message property and it is used as the message of our warning dialog.

  • I will show the default window alert by using window.alert because we are focusing on learning higher order component concepts. You can feel free to create your modal and add some styling for it.

  • As mentioned before, we can pass the custom logic to the input component via props. We pass showModal function to the input component through a prop which is also called showModal. It means that we can show the modal by dispatching showModal function from the input component.

  • Step 2: Install validator library. This librayr provides many common functions. Therefore, we can reuse them instead of creating everything from scratch. We need to run npm install validator.

  • Step 3: Import validator library to LoginForm.js file because we would like to validate the user's information.

...// import validator.import validator from "validator";...
  • Step 4: In LoginForm.js file, we write a function to validate the user's credentials.
...const isUserCredentialsValid = () => {    return validator.isEmail(email) && validator.isLength(password, { min: 6 });  };...

2nd NOTE:

  • validator.isEmail is used to ensure that the user's email will follow the email format.

  • validator.isLength(password, { min: 6 }) is used to validate the length of the user's password. The user's password' s length must have at least 6 characters.

  • Step 5: Import the above higher order component into LoginForm.js file.
...// import hoc.import withModal from "../modal/Modal";...
  • Step 6: Wrap LoginForm component inside the higher order component.
...// export LoginForm component.export default withModal(LoginForm);...
  • Step 7: Get showModal function of the higher order component via props.
...const { showModal } = props;...
  • Step 8: Call showModal function if the input user's information is invalid.
.../**   * handle event when the user clicks on "Login" button.   */  const login = () => {    // call firebase authentication service.    if (isUserCredentialsValid()) {      firebaseAuth        .signInWithEmailAndPassword(email, password)        .then((userCredential) => {          // Signed in          const user = userCredential.user;          // ...          console.log(`signed in user`);          console.log(user);        })        .catch((error) => {          console.log(error);        });    } else {      showModal({ message: "Your email or password is not correct" });    }  };...

After finish all of the above steps, LoginForm componnet will look like this:

/** * Github: https://github.com/hieptl/netflix-clone. * Dev.to: https://dev.to/hieptl/learn-react-by-building-netflix-1127 */// import react.import { useState } from "react";// import firebase authentication.import { firebaseAuth } from "../../firebase/firebase";// import hoc.import withModal from "../modal/Modal";// import validator.import validator from "validator";/** * create LoginForm component. */function LoginForm(props) {  // create email and password state to store user's credentials.  const [email, setEmail] = useState("");  const [password, setPassword] = useState("");  const { showModal } = props;  const isUserCredentialsValid = () => {    return validator.isEmail(email) && validator.isLength(password, { min: 6 });  };  /**   * handle event when the user clicks on "Login" button.   */  const login = () => {    // call firebase authentication service.    if (isUserCredentialsValid()) {      firebaseAuth        .signInWithEmailAndPassword(email, password)        .then((userCredential) => {          // Signed in          const user = userCredential.user;          // ...          console.log(`signed in user`);          console.log(user);        })        .catch((error) => {          console.log(error);        });    } else {      showModal({ message: "Your email or password is not correct" });    }  };  /**   * update email state when the user inputs the email field.   * @param {*} e - synthetic event to get the latest email's value.   */  const onEmailChanged = (e) => {    // get email value.    const updatedEmail = e.target.value;    // update email state.    setEmail(() => updatedEmail);  };  /**   * update password state when the user input the password field.   * @param {*} e - synthetic event to get the latest password's value.   */  const onPasswordChanged = (e) => {    // get password value.    const updatedPassword = e.target.value;    // update password state.    setPassword(() => updatedPassword);  };  return (    <div className="login-body">      <div className="login-body__form">        <h1>Sign In</h1>        <div className="login-body__input mb-16">          <input            type="text"            placeholder="Email or phone number"            onChange={onEmailChanged}          />        </div>        <div className="login-body__input">          <input            type="password"            placeholder="Password"            onChange={onPasswordChanged}          />        </div>        <button className="login-body__submit-btn" onClick={login}>          Sign In        </button>        <div className="login-body__options">          <span>Remember me</span>          <span className="login-body__need-help">Need help?</span>        </div>        <div className="login-body__footer">          <div className="login-body__fb">            <img              src="https://assets.nflxext.com/ffe/siteui/login/images/FB-f-Logo__blue_57.png"              alt="fb"            />            <span>Login with Facebook</span>          </div>          <div className="login-body__new-to-nl">            <span>New to Netflix ?</span>            <span className="login-body__sign-up">Sign up now.</span>          </div>          <div className="login-body__google_captcha">            This page is protected by Google reCAPTCHA to ensure you're not a            bot.            <span className="login-body__learn-more">Learn more.</span>          </div>        </div>      </div>    </div>  );}// export LoginForm component.export default withModal(LoginForm);

Conclusion

In this course, we have learn about higher order components by building Netflix. I hope that you can apply higher order components to your projects. If you feel the project is useful, please help me share it to the community and give me Github

References

[1]. https://reactjs.org/docs/higher-order-components.html


Original Link: https://dev.to/hieptl/learn-react-higher-order-components-hocs-by-building-netflix-3h73

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To