React basic in a post.

hte305

Ha Tuan Em

Posted on February 11, 2020

React basic in a post.

React is awesome library for building something great

-> This article is personal knowledge so if something wrong, you can comment my post, it's going to help me a lot.

What is jsx ?

const element = <h1>Hello, world!</h1>;
Enter fullscreen mode Exit fullscreen mode

It's include of javascript and JSX is going to change you mind about template of language. JSX is rendering html base javascript logic inside.

Why is JSX ?

React embraces events logic in UI like how events are handles, how state changes or how data processes before display, etc...

Instead of artificially separating UI and logic to different file. So React is going to close both this part to a file. It is going to help code clearly and maintenance easily. (SoC to find out)

Rendering Elements

In template React when you create new some component, tag

<div id="root"></div>

in index.html file in public folder. This is DOM node and every element React will be rendering inside this div tag.

Applications built with just React usually have a single root DOM node

ReactDOM.render(<SampleComponent />, document.getElementById("sampleElement"))
Enter fullscreen mode Exit fullscreen mode

public/index.html

<!-- .... -->
<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
</body>
<!-- .... -->
Enter fullscreen mode Exit fullscreen mode

src/index.js

ReactDOM.render(<App />, document.getElementById("root"));
Enter fullscreen mode Exit fullscreen mode

Components and Props

Components is "let you split the UI into independent, reusable pieces, and think about each piece in isolation." - reactjs.org.

Component is return a React element.

Props is a object data argument, readonly and component accepts a single "props" inside.

Props is object, readonly and one props in one component

Example :

function App() {
  return (
    <div className="App">
      <Avatar name="Ha Tuan" source="https://picsum.photos/400" />
    </div>
  );
}

function Avatar(props) {
  return (
    <div>
      <img src={props.source} />
      <p>{props.name}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

State and Lifecycle

Basically, State is object property in class React.Component like object in Class javascript. You can change value or delete key object in state anyway.

class Counter extends Component {
  state = {
    counter: 0
  };

  handleIncrement = () => this.setState({ counter: this.state.counter + 1 });
  handleDecrement = () => this.setState({ counter: this.state.counter - 1 });

  render() {
    return (
      <div>
        <button onClick={this.handleIncrement}>+</button>
        <span>{this.state.counter}</span>
        <button onClick={this.handleDecrement}>-</button>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Lifecycle you can find out in programmingwithmosh.com for more information.

State and LifeCycle is very important in React Component.

Handling Events

"Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences:

  • React events are named using camelCase, rather than lowercase.
  • With JSX you pass a function as the event handler, rather than a string."

reactjs.org

Example someway for handle events in React element :

  • Using arrow function
class Alert extends Component {
  handleOnClick = () => {
    alert("Method is called");
  };

  render() {
    return (
      <div>
        <button onClick={this.handleOnClick}>Click me for show alert !</button>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Binding events in constructor
class Alert extends Component {
  constructor(props) {
    super(props);
    this.handleOnClick = this.handleOnClick.bind(this);
  }

  handleOnClick() {
    alert("Method is called");
  }

  render() {
    return (
      <div>
        <button onClick={this.handleOnClick}>Click me for show alert !</button>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Using handle events in function Component
function Alert() {
  function handleOnClick(e) {
    alert("Alert is called");
  }
  return (
    <div>
      <button onClick={handleOnClick}>Click me for show alert !</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Conditional Rendering

  • Using if else inline or original.
function LogoutButton(props) {
  return <button onClick={props.OnClick}>Log out</button>;
}

function LoginButton(props) {
  return <button onClick={props.OnClick}>Log in</button>;
}

class Authenticate extends Component {
  state = {
    isAuthenticate: false
  };

  handleOnLogout = () => this.setState({ isAuthenticate: false });
  handleOnLogin = () => this.setState({ isAuthenticate: true });
  render() {
    const element = this.state.isAuthenticate ? (
      <LogoutButton OnClick={this.handleOnLogout} />
    ) : (
      <LoginButton OnClick={this.handleOnLogin} />
    );
    return (
      <div>
        <h1>Page Authenticate</h1>
        {element}
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Using Inline If with [ Logical && Operator ] or [ Logical || Operator ]
class ShoppingCart extends Component {
  state = {
    items: 0
  };
  render() {
    return (
      <div>
        <h1>Shopping Cart</h1>
        {/* try both method */}
        {this.state.items <= 0 && <p>Nothing item in cart.</p>}
        {this.state.items <= 0 || <p>Nothing item in cart.</p>}
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Lists and Keys

In React, it's usually use method map() or any method which you want. That's for rendering element in components. Do simple todo list for understand :

import React, { Component } from "react";

class TodoList extends Component {
  state = {
    todos: [
      {
        id: 0,
        title: "Learing react"
      }
    ],
    title: ""
  };

  handleOnChange = e => {
    this.setState({
      title: e.target.value
    });
  };

  handleOnRemove = id => {
    this.setState({
      todos: this.state.todos.filter(todo => todo.id !== id)
    });
  };
  handleOnAddTodo = e => {
    e.preventDefault();
    const newTodo = {
      id: this.state.todos.length + 1,
      title: this.state.title
    };
    this.setState({
      todos: [newTodo, ...this.state.todos],
      title: ""
    });
  };
  render() {
    const todoList = this.state.todos.map((todo, index) => (
      // change key={todo.id} to key={index} you are going to see something wrong in this case
      <TodoItem onRemove={this.handleOnRemove} {...todo} key={todo.id} />
    ));
    return (
      <div>
        <form>
          <input
            value={this.state.title}
            onChange={this.handleOnChange}
            placeholder="add something"
          />
          <button onClick={this.handleOnAddTodo}>add</button>
        </form>
        <hr />
        {todoList}
      </div>
    );
  }
}

function TodoItem(props) {
  return <li onClick={e => props.onRemove(props.id)}>{props.title}</li>;
}

export default TodoList;
Enter fullscreen mode Exit fullscreen mode

"Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity" - reactjs.org

Don't using indexes for keys if your array something change like delete object in array. Because this can be make issues with component state.

Forms

"HTML form elements work a little bit differently from other DOM elements in React, because form elements naturally keep some internal state" - reactjs.org

Some control form in React


<input type="text" name="Tittle" className="form-control" />
<textarea value="" name="Description" className="form-control" />
<select value="" onChange={this.someHandleOnChange} multiple={true}>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>
Enter fullscreen mode Exit fullscreen mode

But when you have a lot of control but type of data is the same. You can put all event onChange in a function like this for save your time and clean code :

handleOnChange = (e) => {
  this.setState({[e.target.name] : e.target.value});
}
Enter fullscreen mode Exit fullscreen mode

With type of data is file you can find out in my post Upload file with multer in Nodejs.

Summary

React is awesome library, you can try it if you see something interesting. Important in this library is manager state, because if we project is too large then state in application maybe is very disorderly. In this case I think we must be know Redux and apply to application. It's save our time. But it's library is not friendly for beginner or don't know Javascript. I recommend we should be know OOP in javascript. It's great for our time.

Thanks you for reading.
Have a nice day !

πŸ’– πŸ’ͺ πŸ™… 🚩
hte305
Ha Tuan Em

Posted on February 11, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related