Category: Hooks

Using ReactQuery with React instead of Axios + hooks

In your React app you can use ReactQuery and ReactQueries for request caching, background updates and stale data out of the box with zero-configuration, instead of just Axios + hooks.

UseQuery : 1 api request

import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
...
const getServices = () => {
        return axios.get('https://jsonplaceholder.typicode.com/posts');
};
...
const { data, isError, isLoading } = useQuery(['services'], getServices);

if (isLoading) {
    return <p>Loading...</p>;
}

if (isError) {
    console.error('error');
}

return <ServiceComponent data={data} />;

UseQueries : 2+ api request

Index.tsx

import { useQueries } from '@tanstack/react-query';
import axios from 'axios';
...
const getServiceOne = () => {
        return axios.get('https://jsonplaceholder.typicode.com/posts');
};
...
const results: any = useQueries({
    queries: [
      { queryKey: ['serviceOne'], queryFn: getServiceOne, staleTime: Infinity },
      { queryKey: ['serviceTwo'], queryFn: getServiceTwo, staleTime: Infinity },
    ],
});

const serviceOneResult = results[0];
const serviceTwoResult = results[1];

  const isError = serviceOneResult.error || serviceTwoResult.error;
  const isLoading = serviceOneResult.isLoading || serviceTwoResult.isLoading;

  if (isLoading) {
    return <p>Loading...</p>;
  }

  if (isError) {
    console.error('error');
  }

  return (
    <ServiceComponent
      dataOne={serviceOneResult.data}
      dataTwo={serviceTwoResult.data}
    />
  );

Color picker with React.JS

Example of a color picker made with React.JS

In order to have a color picker on our React.JS application, we can use the SketchPicker library

Full example

Color: <TextField variant="outlined" id="standard-basic" style={{padding: 5, width: '90%', background: color}} value={color?color:''} onChange={(e) => { setColor(e.target.value); }} />
<SketchPicker 
   color={ color?color:'#fff' }
   onChangeComplete={ (colorSelected) => {
         setColor(`${colorSelected.hex}${decimalToHex(colorSelected.rgb.a)}`);
      } 
   }
   presetColors={['#D0021B', '#F5A623', '#F8E71C', '#8B572A', '#7ED321', '#417505', '#BD10E0', '#9013FE', '#4A90E2', '#50E3C2', '#B8E986', '#000000', '#4A4A4A', '#9B9B9B', '#FFFFFF']}
/>

Alerting user with a small messaga bubble – Snackbar – React.JS

In your web app, you will have to notice the user when he is doing some actions in your user interface. We can do it with a small message bubble called Snackbar, here is what it looks like:

How we will do it

setSnackSeverity("error");
setSnackMessage("The last cell cannot be deleted.");
setOpenError(true);

In your code, we will use these 3 lines to:
– Set the severity “error”, there are 4 types of severity

– Set the error message that will be displayed “The last cell cannot be deleted.”
– Show the error message (during few seconds)

Full example

import Snackbar from '@material-ui/core/Snackbar';
import MuiAlert, { AlertProps } from '@material-ui/lab/Alert';
function Alert(props) {
  return <MuiAlert elevation={6} variant="filled" {...props} />;
}
...
const [snackSeverity, setSnackSeverity] = useState('error');
const [openError, setOpenError] = useState(false);
const [snackMessage,setSnackMessage] = useState('Error');
...
setSnackSeverity("error");
setSnackMessage("The last cell cannot be deleted.");
setOpenError(true);
...
<Snackbar
   anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
   open={openError}
   onClose={(e)=>setOpenError(false)}
   autoHideDuration={3000} 
   >
     <Alert onClose={(e)=>setOpenError(false)} severity={snackSeverity}>
       {snackMessage}
     </Alert>
</Snackbar>

React.JS • Full list of all icons

Examples of listing the icons in React.JS / React Native

Listing all the icons

List of all the icons

Searching icons name

Searching an icon name

How to do it ?

Importing all the icons

Import the CSS your icons in /public/index.html

<link rel="stylesheet" href="http://cdn.materialdesignicons.com/5.4.55/css/materialdesignicons.min.css" />

Use it in your source code

Use your icons in the code source in /src/App.js like that:

<span> 
   <i class={`mdi mdi-${icon?icon:''}`} aria-hidden="true"></i>
</span>

Loop on all icons

If you want a list of icons then you can loop on the list of icons, let’s say you have put all your icons in a file called iconlist.js

export const icons = [
"ab-testing",
"abjad-arabic",
"abjad-hebrew",
"abugida-devanagari",
"abugida-thai",
"access-point",
"access-point-check",
"access-point-minus",
"access-point-network",
"access-point-network-off",
"access-point-off",
"access-point-plus",
"access-point-remove",
"account",
"account-alert",
"account-alert-outline",
"account-arrow-left",
"account-arrow-left-outline",
"account-arrow-right",
"account-arrow-right-outline",
"account-box",
"account-box-multiple",
"account-box-multiple-outline",
"account-box-outline",
"account-cancel",
"account-cancel-outline",
"account-cash",
"account-cash-outline",
"account-check",
...
];

Then you can import the icons in you App.js and use it:

import { icons } from './icons';
...
{ icons.map((icon, index) => (
   <div style={{fontWeight: 'bold'}}> <i class={`mdi mdi-${icon}`} aria-hidden="true"></i> {icon} </div>
))}

You can then add a filter if you want to check that the icons contain part of the string name :

const [searchIcon, setSearchIcon] = useState(null);
...
{ icons.filter(icon => icon.includes(searchIcon) ).map((icon, index) => (
    <div style={{fontWeight: 'bold'}}> <i class={`mdi mdi-${icon}`} aria-hidden="true"></i> {icon} </div>
  )
)}

React.JS / React Native : Class VS Hooks

No matter if you are using React.JS or React Native, Javascript or Typescript, you can choose these 2 ways to manage the states.

Using Class OR using Hooks : What are the differences ?

Class

import React, { Component } from 'react'; 

[...]

class Button extends Component {
    constructor(props){
        super(props);

        this.state = {
            touched: false,
            selected: false,
        }
    }

  toggleTouched = () => {
    this.setState({
      touched: true
    });
  } 
    
    render(){ 
        return( 
            <button id="button" onMouseOver={this.toggleTouched} >
                click me!!
            </button>
        );
    } 
}

export default Button;

Using a class, you need to create a class that extends from a React Component. Like every class in every languages, you use the constructor to init the class. We use it to set the default values to our states. Moreover, we need to use “this” in that class to know that we are getting the values or the function in this class, this refer to the context.


Hooks

import React, { memo, useState, useEffect } from 'react'; 

[...]

const Button = memo((props) => {
  const [touched, setTouched] = useState(false);
  const [selected, setSelected] = useState(false); 
 
  const toggleTouched = () => {
    setTouched(true);
  } 

  return( 
     <button id="button" onMouseOver={toggleTouched} >
        click me!!
     </button>
  );
}); 

export default Button;

Same component, working the same too, but we need a bit less code.
We don’t need a constructor, to set the default value to our states, we just use the parameter of useState.
We don’t need the “this” keyword too, because we don’t are in a class anymore.

Instead of using setState, we use useState.
When it starts if “use…”, we are talking about hooks :
– useState : set a state with the name, the setter, the initial value
– useEffect : refresh if specific state is changed, we can use it as “ComponentWillMount” if we don’t give a state in 2nd param
– useRef : Reference for JSX
– useCallback, …etc.

Hooks seems to be the new best way to manage our states and you should use it as it may save a lot of times and lines in your code.