Higher order components example

soom·2020년 10월 6일
0
post-thumbnail
post-custom-banner

Let's dealing with Higher Order Components!
HOC(Higer Order Components) usually inside HOC Folder in src folder.
Let's create Rainbow.js files inside HOC folder.
the className is coventional usage of materialize style sheet.

e.g.) red-text, blue-text etc ...

Here props at the first return is pointing out theWrappedComponent.
then returning jsx with module <WrappedComponent />.

Plus, need to update props of <WrappedComponent /> need curly brace with {...props} for applying it.

Rainbow.js

import React from "react";

const Rainbow = (WrappedComponent) => {
  const colours = ["red", "pink", "orange", "blue", "green", "yellow"];
  const randomColour = colours[Math.floor(Math.random() * 6)];
  const className = `${randomColour}-text`;

  return (props) => {
    return (
      <div className={className}>
        <WrappedComponent {...props} />
      </div>
    );
  };
};

export default Rainbow;

Now, go About.js!
Import the HOC module we made, Rainbow from Rainbow.js.
Then wrap the default export About by Rainbow().

import React from "react";
import Rainbow from "../hoc/Rainbow";

const About = () => {
  return (
	//...
  );
};

export default Rainbow(About);
profile
yeeaasss rules!!!!
post-custom-banner

0개의 댓글