Showing posts with label ReactJs. Show all posts
Showing posts with label ReactJs. Show all posts

React: File download

 React: File download


Got a requirement to save api response data (blob) to a file.


setLoading(true);
const responseData = await callApi();
setLoading(false);
var blob = new Blob([responseData], { type: "application/json" });
let url = window.URL.createObjectURL(blob);

// Creating the hyperlink and auto click it to start the download
let link = document.createElement("a");
link.href = url;
link.download = "samplefile.json";
link.click();

React: Preload Images

 React: Preload Images


I had a situation that lot of time taken to load images, which are loaded dynamically. One solution was to preload the images whenever we get the URL so that images will be available in cache and it will load quickly.

Below solution worked

useEffect(()=>{
images.forEach((image) => {
const img = new Image();
img.src = baseurl + image.fileName;
});
}, [])


References:

https://stackoverflow.com/questions/42615556/how-to-preload-images-in-react-js


 

Tailwind CSS: Dark and Light Theme

 Tailwind CSS: Dark and Light Theme 

I am using Tailwindcss in my react app. One of the requirement was to provide light and dark theme for the web app. This can be achieved easily with Tailwind.

1. Specify colours and styles for light and dark theme. For light theme just use class-name as it is and for  dark theme, use dark:class-name.

eg: bg-white dark:bg-gray-700


Switch between white and dark theme

To switch between the themes, there are many methods. I chose using class. Using class, need to mention darkMode: "class" in tailwind.config.js.

/** @type {import('tailwindcss').Config} */
module.exports = {
darkMode: "class",
theme: {
extend: {},
},
plugins: [],
content: ["./src/**/*.{js,jsx,ts,tsx,html}", "./public/index.html"],
};

Then we can add a button, on click add/remove class-name "dark" to/from <html> to toggle between dark between light theme.

document.documentElement.classList.toggle("dark");

or 

document.documentElement.classList.add("dark");
document.documentElement.classList.remove("dark");



Note: To keep the theme selection, we can store the value to localstorage and retrieve it on  load for better user experience.


Reference: https://tailwindcss.com/docs/dark-mode



React Router V6 (react-router-dom) Dynamic Routing

 React Router V6(react-router-dom) Dynamic Routing


I was trying to implement dynamic routing with router v6 similar to that with v4 . 

eg in v4

const routes = [
{ path: '/', key:"home", component: Home },
{ path: 'page1',key:"page1", component: Page1 },
{ path: 'page2', key:"page2" component: Pag2 }
];


<Route path={variable} component 

<Router>
<Switch>
{routes.map(page => (<Route key={page.key} path={page.path} component={page.component} />))}
</Switch>
</Router>

This can be achieved in router v6 using useRoutes

Router.tsx

import { useRoutes } from "react-router-dom";

import Home from "../pages/Home";
import Page1 from "../pages/Page1";
import Page2 from "../pages/Page2";

export default function Router() {
return useRoutes([
{ path: "/", element: <Home /> },
{ path: "/page1", element: <Page1 /> },
{ path: "/page2", element: <Page2 /> },
]);
}


App.tsx

import React from "react";
import { BrowserRouter } from "react-router-dom";
import Router from "./helpers/Router";
function App() {
return (
<div>
<BrowserRouter>
<Router />
</BrowserRouter>
</div>
);
}

export default App;

References:

https://reactrouter.com/en/main/hooks/use-routes


React : Disable Browser Forward and Backward Button or Prevent Navigation

 React : Disable Browser Forward and Backward Button or Prevent Navigation 


To prevent navigation to specific route, we need to use history.block() - https://github.com/remix-run/history/blob/dev/docs/blocking-transitions.md


The browser backward button click action will be pop() and the browser forward button click action will be push(). We need to listen and handle these actions to block navigation.  


 

React: Create React App not working in Internet explorer

React: Create React App not working in Internet explorer

I faced this issue today. When I created a new react application using CRA. It was not working in internet explorer browser. I solved it by using polyfills. I followed below steps


1. installed react-app-polyfill

yarn add react-app-polyfill --save


2. imported it in index.js (should be first line)

import 'react-app-polyfill/ie11'; 
import 'react-app-polyfill/stable';

3. Updated browsers in package.json
"browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "ie 11",
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
4. Deleted node_modules 
5 yarn and yarn start. Worked !!!



useSelector useDispatcher React Example

useSelector useDispatcher - React Example

We can use useSelector and useDispatcher instead of using connect().

import React, { useEffect } from 'react';
import { useSelectoruseDispatch } from "react-redux";
import './App.css';

import {dataActionfrom './actions/getDataAction';

function App() {
  
  const data = useSelector(state => state.dataReducer);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(dataAction())
  });

  return (
    <div className="App">
      <header className="App-header">
        <h1>{data}</h1>
      </header>
    </div>
  );
}

export default App;

Please find github project - https://github.com/codingtechlife/useSelector_useDispatcher_example


Facebook like skeleton loader in React


Facebook like skeleton loader in React


You have noticed the loader displayed in facebook and other new websites when content is loading. The loader can be implemented in react application using  react-content-loader

demo:  https://danilowoz.com/create-content-loader/

To install:
npm i react-content-loader --save

yarn add react-content-loader


Usage: 
1. Preset Example 

import ContentLoader, { Facebook } from "react-content-loader";
const MyLoader = () => <ContentLoader />;
const MyFacebookLoader = () => <Facebook />;

2. Custom

import React from "react";
import ContentLoader from "react-content-loader";

const CustomLoader = () => (
  <div style={{ width: "100%", minHeight: "500px" }}>
    <ContentLoader style={{ width: "100%", height: "500px" }}>
      <rect x="65%" y="0" rx="5" ry="5" width="100%" height="30" />
      <rect x="10" y="40" rx="5" ry="5" width="100%" height="40" />
      <rect x="10" y="100" rx="5" ry="5" width="100%" height="30" />
      <rect x="10" y="150" rx="5" ry="5" width="100%" height="30" />
      <rect x="10" y="200" rx="5" ry="5" width="100%" height="30" />
      <rect x="10" y="250" rx="5" ry="5" width="100%" height="30" />
      <rect x="10" y="300" rx="5" ry="5" width="100%" height="30" />
      <rect x="10" y="350" rx="5" ry="5" width="100%" height="30" />
      <rect x="10" y="400" rx="5" ry="5" width="100%" height="30" />
      <rect x="75%" y="450" rx="5" ry="5" width="100%" height="30" />
    </ContentLoader>
  </div>
);
export default CustomLoader;

Note: I have faced issue in providing 100% width for the loader. The above code fixed issue and take 100% width of the container.

create-react-app - Create ReactJs Application Tutorial

create-react-app - Create ReactJs Application Tutorial


I have been trying to learn ReactJs and create some sample applications with it. Today found create-react-app (https://github.com/facebookincubator/create-react-app) which will help us to generate sample reactjs application without knowing the reactjs. Only thing we need to do are,

1. Install latest nodejs version.

2. Install create-react-app
npm install -g create-react-app

3. Generate reactjs application using create-react-app
create-react-app myApp

4.       Run the application
cd myApp
npm start

The application will be started at http://localhost:3000.