DEV Community

Cover image for REACT basics
Emran H Khan
Emran H Khan

Posted on

REACT basics

What is React: React is JavaScript library created by Facebook. It is a tool for building UI components. React doesn't manipulate the browser's DOM directly, instead it creates copy of the DOM and save it in memory. This copied DOM is generally known as the 'VIRTUAL DOM'. React then finds out what changes have been made, and changes only that part in the DOM.

Skills to learn React:
1. HTML & CSS
2. JSX
3. Fundamental of JavaScript and ES6
4. Package manager (Node+Npm)
5. Git and CLI

The Render Function: React renders HTML to web page by using a function called ReactDOM.render(). This function takes two arguments, HTML code and HTML element. The purpose of this function is to display the specified HTML code inside the specified element.

Display a span inside the 'root' element:

ReactDOM.render(<span>Hello World!</span>, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

The result is displayed in the <div id='root'> element:

<body>
  <div id='root'></div>
</body>
Enter fullscreen mode Exit fullscreen mode

The HTML code here uses JSX which allows you to write HTML tags inside the JavaScript code.

JSX: JSX stands for JavaScript XML. It allows us to write HTML in React. JSX converts the HTML into react elemts.

  1. With JSX:
const newElement: <h1>Learning JSX!</h1>
ReactDOM.render(newElement, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode
  1. Without JSX:
const newElement = React.createElement('h1', {}, 'Not using JSX');
ReactDOM.render(newElement, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

It is clearly seen from the above example, it is far more easier to write JSX which eventually transpile our HTML to JavaScript at runtime.

Expression can be written in JSX using the curly braces {}.
And to write multiple HTML lines you have to put parentheses around the HTML and wrap everything in a single Top level element.
For example,

const newElement = (
  <div>
    <h1>I am a header.</h1>
    <p> I am a paragraph.</p>
  </div>
);
Enter fullscreen mode Exit fullscreen mode

Functional Component: A component is an independent, reusable code block which divides the UI into smaller pieces. A functional component is basically a JavaScript/ES6 function that returns a React element(JSX). It needs to exported to be used later in somewhere else.

const Welcome = (props) => {
  return <h1>Hello, {props.name}</h1>
}

export default Welcome;
Enter fullscreen mode Exit fullscreen mode

And to use it we need to import it.

import Welcome from './Welcome';

const App = () => {
  return(
    <div className="App">
      <Welcome />
    <div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Props: Props is short for properties ant they are used to pass data between React components. React's data flow between components is uni-directional (from parent to child only);
For example, if you want to pass something from app to component you have to pass it like an attribute with suitable name.
Here, I am passing 'name' from the App component to Welcome component. If you need to pass data dynamically just use the curly braces.

import Welcome from './Welcome';

const App = () => {
  return(
    <div className="App">
      <Welcome name="Justin" />
    <div>
  )
}
Enter fullscreen mode Exit fullscreen mode

So, in the Welcome component we will get the data in the 'props'.
And we can use it like this.

const Welcome = (props) => {
  return <h1>Hello {props.name}!</h1>
} 
Enter fullscreen mode Exit fullscreen mode

State: React has another special built-in object called state, which allows components to create and manage their own data. So unlike props, components cannot pass data with state, but they can create and manage it internally.
React components are rendered (with state) based on the data in the state. State holds the initial information. So, when state changes, React gets informed and immediately re-renders the part of the DOM which actually needs to be changed. There is method called 'setState' which triggers the re-rendering process for the updated parts. React gets informed, knows which parts to change, and does it quickly without re-rendering the whole DOM.
In functional components, with the help of React Hooks we can use this 'state'.
We will implement a simple counter using React's useState hook.

import React, { useState } from "react";

function Counter() {
  // Set the initial count state to zero, 0
  const [count, setCount] = useState(0);

  // Create handleIncrement event handler
  const handleIncrement = () => {
    setCount(prevCount => prevCount + 1);
  };

  //Create handleDecrement event handler
  const handleDecrement = () => {
    setCount(prevCount => prevCount - 1);
  };
  return (
    <div>
      <div>
        <button onClick={handleDecrement}>-</button>
        <h5>Count is {count}</h5>
        <button onClick={handleIncrement}>+</button>
      </div>
      <button onClick={() => setCount(0)}>Reset</button>
    </div>
  );
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

And use this component is the App.js like so:

import React from "react";
import Counter from "../Counter";

export default function App() {
  return (
    <div className="App">
      <Counter/>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

useEffect: A functional React component uses props and/or state to calculate the output. If the functional component makes calculations that don’t target the output value, then these calculations are named side-effects.

useEffect() hook accepts 2 arguments:

useEffect(callback[, dependencies]);

callback is the callback function containing side-effect logic. useEffect() executes the callback function after React has committed the changes to the screen.

dependencies is an optional array of dependencies. useEffect() executes callback only if the dependencies have changed between renderings.
Put your side-effect logic into the callback function, then use the dependencies argument to control when you want the side-effect to run. That’s the sole purpose of useEffect().

React Events: Just like HTML, React can perform actions based on user events. Reach has the same events as HTML: click, change, mouserover etc.
React events are written in camelCase sytax: onClick instead of onclick.

import React from 'react';
import ReactDOM from 'react-dom';

function shoot() {
  alert("Great Shot!");
}

const myelement = (
  <button onClick={shoot}>Take the shot!</button>
);

ReactDOM.render(myelement, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

If you want to pass an argument in the event handler, then you have to wrap the handler into an anonymous arrow function.

import React from 'react';
import ReactDOM from 'react-dom';

function shoot(condition) {
  if (condition) {
    alert("Great Shot!");
  }
  alert("Keep going on");
}

const myelement = (
  <button onClick={() => shoot(true)}>Take the shot!</button>
);

ReactDOM.render(myelement, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

React CSS: To style an element with the inline style attribute, the value must be a JavaScript object. Properties with two name, like background-color, must be written in camel case syntax.

const MyHeader = () => {
  return (
      <div>
      <h1 style={{color: "white", backgroundColor: 'black'}}>Hello Style!</h1>
      <p>Add a little style!</p>
      </div>
    );
 }
Enter fullscreen mode Exit fullscreen mode

You can also create an object with styling information, and refer it in the style attribute:

const myStyle = {
  color: "white", 
  backgroundColor: 'black'
}

const MyHeader = () => {
  return (
      <div>
      <h1 style={myStyle}>Hello Style!</h1>
      <p>Add a little style!</p>
      </div>
    );
 }
Enter fullscreen mode Exit fullscreen mode

Top comments (7)

Collapse
 
nathandaly profile image
Nathan Daly

Love a bit of RECT

Collapse
 
sroehrl profile image
neoan

Do you think the title should be RECTified?

Collapse
 
nathandaly profile image
Nathan Daly

It should but I don't want to diRECTly point the error out :/

Thread Thread
 
sroehrl profile image
neoan

I see. But would you go so far as to call it incorRECT?

Collapse
 
emranhkhan profile image
Emran H Khan

sorry about that

Thread Thread
 
sroehrl profile image
neoan

All good, we're just having fun ;-)
BTW: Check how to specify language in code markup. It makes things easier to read.

Collapse
 
emranhkhan profile image
Emran H Khan

sorry for the mistake