Babel and browserslist

Transpiling Code:

// Modern Code (ES6+):
const add = (a, b) => a + b;

// Transpiled Code (ES5):
var add = function (a, b) {
  return a + b;
};

Polyfills

// Modern Code:
if (myArray.includes(5)) {
  // ... do something
}

// Polyfilled Code (simplified representation):
if (polyfill_includes(myArray, 5)) {
  // ... do something
}

Important Note:

  "browserslist": [
    "last 10 Chrome version"
  ]

We used npx parcel index.html to run our project. This command can both run and build our project, but it's not the most convenient approach.

To make things easier, we can define scripts inside our package.json file:

"scripts": {
  "start": "parcel index.html",
  "build": "parcel build index.html"
}

So now that we have set up scripts, we can run our project using npm run start.

When we are using Parcel our console.log() statements are not removed by default from our build. So, we will need to configure Parcel to removeconsole.log as well.

Configuring Parcel to remove console.logs

Search for babel-plugin-transform-remove-console OR click here

To install, use the following code:

npm install babel-plugin-transform-remove-console --save-dev

Keys in React

How does React.createElement() API works?

<div class="header">
  <ul>
    Namaste React
  </ul>
  <ul>
    <li>About us</li>
    <li>Support</li>
    <li>Home</li>
  </ul>
</div>

To convert the above code using React.createElement(), here's the equivalent:

const div = React.createElement("div", { className: "header" }, [
  React.createElement("ul", { key: "1" }, "Namaste React"),
  React.createElement("ul", { key: "2" }, [
    React.createElement("li", { key: "1" }, "About Us"),
    React.createElement("li", { key: "2" }, "Support"),
    React.createElement("li", { key: "3" }, "Home"),
  ]),
]);
const root = ReactDOM.createRoot(document.querySelector("#root"));
root.render(div);

To Solve this Issue, React Introduce JSX

function App() {
  return (
    <div id="header">
      <ul>Namaste React</ul>
      <ul>
        <li key="1">About Us</li>
        <li key="2">Support</li>
        <li key="3">Home</li>
      </ul>
    </div>
  );
}

Note- JSX is not a requiremnet for using React. Using React without JSX is especially convenient when you don’t want to set up compilation in your build environment.

Read More

React Elements

const element = <h1>Hello, world</h1>;
 root.render(element)

React Component

const HeaderComponent = () => {
  return (
    <div>
      <h1>Namaste React functional Component</h1>
      <h2>This is h2 tag</h2>
    </div>
  );
};
root.render(<HeaderComponent />);

How do we call elements and components inside an existing component?

const Component = () => {
  return (
    <div>
      {element} //react element
      {<HeaderComponent />} //one way
      {HeaderComponent()} //second way
      <h1>Normal functional Component</h1>
    </div>
  );
};

Component Composition