Categories
JavaScript React

Introduction to React Router

React is a library for creating front end views. It has a big ecosystem of libraries that work with it. Also, we can use it to enhance existing apps.

To build single-page apps, we have to have some way to map URLs to the React component to display.

In this article, we’ll look at the basic usage of React Router.

Installation

To use React Router, we have to install it. We can do that by running:

npm i react-router-dom

Basic Usage

React Router has a few basic components.

BrowserRouter

First, there’s the BrowserRouter to do the routing with the HTML5 history API.

It takes a few props:

  • basename — a string prop for the base URL for all locations.
  • getUserConfirmation — a function prop we use to confirm navigation. Defaults to using window.confirm .
  • forceRefresh — a boolean prop that’s true if we want a full refresh on page navigation. It’s useful for imitating traditional server-render apps.
  • keyLength — a number prop that sets the length of location.key . Defaults to 6.
  • children — a React component to render. Before React 16, we can only use a single child element. If we want to render more than one element, we can wrap it in a div.

Switch

Next, there’s the Switch component. It renders the first child Route or Redirect that matches the location.

Switch renders a route exclusively. Route that matches the location renders inclusively.

Switch will only pick one Route to render.

Route

The Route component is the most important component in React Router.

It’s used to map URLs to components and takes the following props:

  • component — we pass in the component to map the URL to by passing in a component to it.
  • render — this prop takes a function that returns something that we want to render.
  • children — a function prop that lets us render something when the path matches Route ‘s path and render something else otherwise.
  • path — a string or array of strings that are paths to match.
  • exact — a boolean prop to that’s true if we want to render only if a path matches exactly.
  • strict — boolean prop that’s true is we only want to match a path with a trailing slash only when the URL entered has a trailing slash. It has no effect when there’re additional URL segments in location.pathname
  • location — an object prop that tries to match its path in the current history location.
  • sensitive — a boolean prop that true if the path is case-sensitive.

Link

The Link component provides accessible navigation around our app.

It takes the following props:

  • to — a string prop with the path that we want to go to. It’s created by concatenating location’s pathname, search and hash properties.
  • to can also be an object that has the pathname, search, state and hash properties. The pathname is a string that has the path to link to. search is a string of the query parameters, hash is a hash top put in the URL, state is the state to persist to the location.
  • to can also be a function which takes the currentlocation as the argument and returns the location representation as a string as an object.
  • replace — a boolean prop that replaces the current entry in the history stack instead of adding one if true
  • innerRef — a function or ref object that we shouldn’t need if we’re using React Router 5.1 or later with React 16. It lets us access the ref of the component.
  • We can any other attribute to the a tag like title , id , className , etc.

Example

We can use the components above together as follows:

import React from "react";  
import ReactDOM from "react-dom";  
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";  
function Home() {  
  return <h2>Home</h2>;  
}

function Foo() {  
  return <h2>Foo</h2>;  
}

function Bar() {  
  return <h2>Bar</h2>;  
}

function App() {  
  return (  
    <Router>  
      <div>  
        <ul>  
          <li>  
            <Link to="/">Home</Link>  
          </li>  
          <li>  
            <Link to="/foo">Foo</Link>  
          </li>  
          <li>  
            <Link to="/bar">Bar</Link>  
          </li>  
        </ul>  
        <Switch>  
          <Route exact path="/">  
            <Home />  
          </Route>  
          <Route path="/foo">  
            <Foo />  
          </Route>  
          <Route path="/bar">  
            <Bar />  
          </Route>  
        </Switch>  
      </div>  
    </Router>  
  );  
}

const rootElement = document.getElementById("root");  
ReactDOM.render(<App />, rootElement);

In the code above, we have the Home , Foo , and Bar components which display some text.

Then we add Router in App and put all our Route s inside so when we click on the Link s, they’ll display the component we specified.

We have:

<Switch>  
    <Route exact path="/">  
        <Home />  
    </Route>  
    <Route path="/foo">  
        <Foo />  
    </Route>  
    <Route path="/bar">  
        <Bar />  
    </Route>  
</Switch>

In the Switch , we have exact in the first Route to only show Home when we go to / .

Then we define 2 more Route s to show Foo when we go to /foo and Bar when we go to /bar .

Conclusion

We can use React Router to map URLs to components. This lets us create a single-page app since we render components according to URLs on the client-side.

Therefore, we’ll have a self-contained app that works on its own without the server rendering things when we type in URLs.

We have the Link to render links, Route to map URLs to components. Router wraps around anything that needs routing.

Switch renders the first child Route or Redirect that matches the location.

Categories
JavaScript React

Intro to React State Management with React-Redux

React is a library for creating front end views. It has a big ecosystem of libraries that work with it. Also, we can use it to enhance existing apps.

To store data in a central place for easy accessibility by components, we have to use some state management solutions. React-Redux is a popular choice.

In this article, we’ll look at how to add it to our React app and simple use cases.

Installation

To install the react-redux package, we have install react-redux and its dependency redux .

We can install both by running:

npm install react-redux redux

with NPM or if we use Yarn:

yarn add react-redux redux

Set Up a Redux Store

After installing both packages, we have to set up our Redux store to hold our data.

To do this we write:

import { createStore } from "redux";

function counterReducer(state = 0, action) {  
  switch (action.type) {  
    case "INCREMENT":  
      return state + 1;  
    default:  
      return state;  
  }  
}

const store = createStore(counterReducer);

The code above creates a Redux store by creating the counterReducer reducer function.

The reducer specifies how the app’s state changes in response to actions sent to the store.

Our counterReducer only accepts one action, which is 'INCREMENT' . We respond to the action by returning the state and adding 1 to it.

There’s also a default case to just return the state value as is.

Then we create a store by calling Redux’s createStore function and passing in our reducer.

It returns the store , which we can pass into our React app.

Connecting the Store to our React App

This is where we need the functions of React-Redux.

We can connect the store to our app so we can store our app’s state in the store by using React-Redux’s connect function.

connect takes 2 functions, which are mapStateToProps and mapDispatchToProps . They’re the first and second argument respectively.

First, we can put the whole app together by connecting our store with the React app as follows:

import React from "react";  
import { Provider, connect } from "react-redux";  
import { createStore } from "redux";  
import ReactDOM from "react-dom";

function counterReducer(state = 0, action) {  
  switch (action.type) {  
    case "INCREMENT":  
      return state + 1;  
    default:  
      return state;  
  }  
}

const store = createStore(counterReducer);

class App extends React.Component {  
  onClick() {  
    this.props.increment();  
  }  
  render() {  
    const { count } = this.props;  
    return (  
      <>  
        <button onClick={this.onClick.bind(this)}>Increment</button>  
        <p>{count}</p>  
      </>  
    );  
  }  
}

const mapDispatchToProps = dispatch => {  
  return {  
    increment: () => dispatch({ type: "INCREMENT" })  
  };  
};  
const mapStateToProps = state => ({  
  count: state  
});App = connect(  
  mapStateToProps,  
  mapDispatchToProps  
)(App);  
const rootElement = document.getElementById("root");  
ReactDOM.render(  
  <Provider store={store}>  
    <App />  
  </Provider>,  
  rootElement  
);

In the code, we have an app that shows a number going up as we click the Increment button.

The first step to connect the store to our React app is to wrap the Provider component around our whole app.

To do this we, wrote the following:

<Provider store={store}>  
  <App />  
</Provider>

Then we define the mapStateToProps and mapDispatchToProps functions as follows:

const mapDispatchToProps = dispatch => {  
  return {  
    increment: () => dispatch({ type: "INCREMENT" })  
  };  
};  
const mapStateToProps = state => ({  
  count: state  
});

In mapStateToProps we return a object to map the state object to a React component prop name as indicated in the property name. The state is the state stored in the Redux store.

So we mapped state to the prop count .

In mapDispatchToProps , we get the dispatch parameter, which is a function used to dispatch our action to the store, and return an object with the name for the function we can access from the props to call and dispatch the action.

So in mapDispatchToProps , increment is our function name. We can call it by running this.props.increment in our App component.

increment is a function that runs dispatch({ type: “INCREMENT” }) .

Then in our App component, we define the onClick method to call this.props.increment to dispatch the ‘INCREMENT’ action to our counterReducer via our Redux store and increase the state by 1.

Then since we have mapStateToProps , the latest value is being observed by App and the latest value is available via this.state.count as indicated in mapStateToProps .

Then when we click the Increment button, we’ll get the number going up by 1.

This will happen with every click.

Conclusion

We can use Redux in our React app by creating a store.

Next, we use the React-Redux Provider component and wrap it around our App entry-point component. We pass our Redux store to the store prop so that we can map the state and dispatch actions to props.

Then connecting it to our store via React Redux’s connect function. We pass in the mapStateToProps and mapDispatchToProps to map the store’s state to our component’s props and map our dispatch function call to our props respectively.

Categories
JavaScript Vue

Add a Tree View to a Vue App with the bootstrap-vue-treeview Library

Creating a tree view from scratch is hard. Therefore, we can make our lives easier with the bootstrap-vue-treeview library.

We can install it by running:

npm install --save bootstrap-vue-treeview

Then we can use it as follows:

main.js

import Vue from 'vue'
import App from './App.vue'
import BootstrapVueTreeview from "bootstrap-vue-treeview";
Vue.use(BootstrapVueTreeview);
Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

App.vue

<template>
  <div id="app">
    <b-tree-view :data="treeData"></b-tree-view>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      treeData: [
        {
          id: 2,
          name: "toyota",
          children: [
            { id: 3, name: "camry" },
            { id: 4, name: "corolla" },
            { id: 5, name: "rav4" },
            { id: 6, name: "prius" }
          ]
        },
        {
          id: 7,
          name: "honda",
          children: [
            { id: 8, name: "accord" },
            { id: 9, name: "civic" },
            { id: 10, name: "cub" }
          ]
        }
      ]
    };
  }
};
</script>

All we had to do is to register the plugin in main.js.

Then we add the b-tree-view component in the template of App.vue and set the data prop to the treeData object, which is returned by the data method.

In addition to the data prop, we can also specify the following props:

Prop Type Description Default value Required
nodeKeyProp String Name of the property containing unique node key "id" No
nodeChildrenProp String Where to look for node children "children" No
nodeLabelProp String Name of the property containing node label "name" No
showIcons Boolean Show/hide icons false No
iconClassProp String Name of the property containing icon class "icon" No
defaultIconClass String Icon class to apply if node has no icon class property null No
prependIconClass String Class to apply to every icon null No
nodesDraggable Boolean Enable or disable drag & drop feature false No
contextMenu Boolean Enable or disable context true No
renameNodeOnDblClick Boolean Enable or disable double click to rename feature true No
contextMenuItems Array of menu items Context menu items [ {code: 'DELETE_NODE', label: 'Delete node' }, { code: 'RENAME_NODE', label: 'Rename node' } ] No

With the code we have. we get:

https://thewebdev.info/wp-content/uploads/2020/04/tree.png

Categories
HTML

Is there an input with Type textarea?

There isn’t a input with type textarea.

Instead, we use the textarea tag to create a text area.

This lets us enter text that has multiple rows and longer than an input would allow.

For instance, we can write;

<textarea rows="5" cols="50">

to display a text area with 5 rows and 50 columns wide.

We should pair that with a label tag for better accessibility.

We can write:

<label for="diary">Diary:</label>
<textarea id="diary" rows="5" cols="50">

The value of the for attribute of label should match with the id of the textarea element.

Then everyone including people that rely on screen readers will know what we should enter in the text area.

Categories
HTML

HTML5 Tags List

HTML5 introduced many new tags. The HTML5 tags list is below:

Structural Tags

Structural tags are for defining the structure of the page. They’re all semantic and provides no formatting.

  • article – defines an article
  • aside – holds some content that’s loosely related to the page content
  • details – a widget from which user can get addition information or controls on demand
  • header – header of a document or section
  • hgroup – a group of headings
  • footer – a footer of a document or section
  • section – a section of a document
  • summary – summary for the details element

Form Tags

These tags are for form structure or controls.

  • datalist – a set of predefined options for an input element
  • keygen – a control for generating a public-private key pair
  • meter – a scalar measurement within a known range

Formatting Tags

These tags are for formatting page content,

  • bdi – text that’s isolated from the surrounding for the purpose of bidirectional text formatting
  • mark – text highlighted for reference purposes
  • output – represent the result of a calculation
  • progress – displays a completion progress of a task
  • rp – provides fallback parentheses for browsers that don’t support ruby annotations
  • rt – defines the pronunciation of characters presented in ruby annotations
  • ruby – defines ruby annotation for pronunciation
  • wbr – a line breaks opportunity

Embedded Content Tags

  • audio – lets us embed sound or audio stream in an HTML document
  • canvas – a region in a document which can be used to draw graphics on the fly
  • embed – embed external application like multimedia content into an HTML documentation
  • figcaption– defines caption or legend for a figure
  • figure – represents a figure as part of a document
  • source – alternative media sources for audio and video
  • time – represents a time or date
  • video – embeds video content in HTML documents