The Best React Tutorial

The Best React Tutorial examples ReactJS





React (also known as React.js) is one of the most popular JavaScript front end development libraries. Here is a collection of React syntax and usage that you can use as a handy guide or reference.

React Component Example

Components are reusable in React.js. You can inject value into props as given below:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Faisal Arkan" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);

name="Faisal Arkan" will give value into {props.name} from function Welcome(props) and returning a component that has given value by name="Faisal Arkan". After that React will render the element into html.

Other ways to declare components

There are many ways to declare components when using React.js. There are two kinds of components, stateless components and stateful components.

Stateful

Class Type Components

class Cat extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      humor: 'happy'
    }
  }
  render() {
    return(
      <div>
        <h1>{this.props.name}</h1>
        <p>
          {this.props.color}
        </p>
      </div>
    );
  }
}

Stateless Components

Functional Components (Arrow Function from ES6)

const Cat = props => {
  return (
    <div>
      <h1>{props.name}</h1>
      <p>{props.color}</p>
    </div>;
  );
};

Implicit Return Components

const Cat = props =>
  <div>
    <h1>{props.name}</h1>
    <p>{props.color}</p>
  </div>;

Fragments are way to render multiple elements without using a wrapper element. When attempting to render elements without an enclosing tag in JSX, you will see the error message Adjacent JSX elements must be wrapped in an enclosing tag. This is because when JSX transpiles, it’s creating elements with their corresponding tag names, and doesn’t know what tag name to use if multiple elements are found.

In the past, a frequent solution to this was to use a wrapper div to solve this problem. However, version 16 of React brought the addition of Fragment, which makes this no longer necessary.

Fragment acts a wrapper without adding unnecessary divs to the DOM. You can use it directly from the React import, or deconstruct it:

import React from 'react';

class MyComponent


Additional Images




Comments

Loading…

We use cookies and other technologies to improve your experience on our website and to analyze our traffic. By browsing our website, you consent to our use of cookies and other tracking technologies.

Accept cookies and close this message
Win now