Showing posts with label React JS. Show all posts
Showing posts with label React JS. Show all posts

August 26, 2022

Mutiple ways to programmatically navigate using React router

 Mutliple ways to navigate between pages in react using react router. 

  • React Router v6
            useNavigate hook can be used.
 
  import { useNavigate } from "react-router-dom"
  const Component = () => {
      let navigate = useNavigate();
      navigate("/pathname", state: { someData }); 
  }

  • React Router v5
            useHistory hook can be used.
 
  import { useHistory } from "react-router-dom"
  const Component = () => {
      let history = useHistory();
      history.push("/pathname"); 
  }


June 24, 2021

React JS Interview Questions and topics

 To evaluate a candidate, recruiters generally asks certain questions so that they can know how much the candidate has hands-on experience and how much is his/her technical capabilities. Below are some of the questions:

  • What is Virtual DOM?
  • Explain how React Routing works?
  • What are the ways to debug React JS application?
  • What are the libraries needed for unit testing. Write a sample unit test.
  • How to configure application so that whenever an user commits code, it first checks the code alignments and other lint issues and fix them automatically.
  • How to configure application so that whenever user pushes code to source control, it first run all unit test cases and on success only it pushes the code to the repo
  • What is Responsize web design?
  • How does Exception Handling works,
  • What type of configuration needed to deploy an react application on mulitple environments.
  • How to maintain configuration data like API URLs, API Keys etc based on different environments in application.
  • Difference between const and let. Write an example.
  • Difference between == and ===, write an example.
  • what is use of pre commit and post commit in package.json?
  • Difference between ES6 functions like filter and find.
  • How to configure redux in the application.
  • How to access lifecycle methods in functional components.
  • Which lifecycle methods we can access using useEffect hook.
  • How and where we can use Spread Operator?
  • What is the use of JWT token and how does it works.

October 30, 2019

How to mock third party libraries and functions in jest using react js


Jest is a library we use for testing JS code whether it's an Angular application or React JS.

Many times we encounter issues while testing code which has third party libraries like mixpanel, moment, redux etc.

To resolve, we need to mock these 3rd party libraries and their respective functions. We need to intercept these libraries by mocking as given below:

1) Create a directory at root as "__mocks__".
2) Let say we need to create mock for moment library. Create a JS file under __mocks__ as moment.js. Keep in mind to have the file name exactly same as declared when importing in source code.
3) Open moment.js file and write below code snippet

const moment = {
  anyFunc: jest.fn()
}
export default moment;

4) Now execute your jest test cases. It will not throw error for moment library.
5) Use can add any mock functions in that file and add expected response and test them.

Hope this helps!

July 23, 2019

How to add a checkbox in primereact datatable

Code snippet to add a checkbox in each row of a primereact datatable.

import React, { Component } from 'react';
import {DataTable} from 'primereact/datatable';
import {Column} from 'primereact/column';

export class DTColumnCheckBoxDemo extends Component {

    constructor() {
        super();
        this.state = {
        }
    }
    render() {
       return (
         <DataTable value={this.state.list}}
            selection={this.state.listItem} onSelectionChange={(e) => this.setState({listItem: e.data})} >
            <Column em="" selectionmode="multiple" />
            <Column field="xyz" header="XYZ" />
            <Column field="abc" header="ABC" />
         </DataTable>
    );
}

In Column tag we need to add selectionmode  attribute to add checkbox in datatable.

July 05, 2019

How to host React JS code with Spring Boot Application

Sometimes we got a requirement where we need to configure react application so that it can be serve in Spring Boot Application. Means, both Spring boot application and react js code can be served from same server.

Following are the steps we need to follow to make it happen:
  1. Put all of your html, js, css, etc. files to src/main/resources/static. Under resources folder create a static folder and under it paste all your frontend code. 
  2. Add one ResourceResolver Class to Spring as below:

    
    @Configuration
    public class Config implements WebMvcConfigurerAdapter {
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            ResourceResolver resolver = new ReactResourceResolver();
            registry.addResourceHandler("/**")
                    .resourceChain(true)
                    .addResolver(resolver);
        }
    
        public class ReactResourceResolver implements ResourceResolver {
            // root dir of react files
            private static final String REACT_DIR = "/static/";
            private static final String REACT_STATIC_DIR = "static";
            private Resource index = new ClassPathResource(REACT_DIR + "index.html");
            private List rootStaticFiles = Arrays.asList("favicon.io",
                    "asset-manifest.json", "manifest.json", "service-worker.js");
    
            @Override
            public Resource resolveResource(
                HttpServletRequest request, String requestPath,
                List locations, ResourceResolverChain chain) {
                return resolve(requestPath, locations);
            }
    
            @Override
            public String resolveUrlPath(
                String resourcePath, List locations,
                ResourceResolverChain chain) {
                Resource resolvedResource = resolve(resourcePath, locations);
                if (resolvedResource == null) {
                    return null;
                }
                try {
                    return resolvedResource.getURL().toString();
                } catch (IOException e) {
                    return resolvedResource.getFilename();
                }
            }
    
            private Resource resolve(
                String requestPath, List locations) {
    
                if (requestPath == null) return null;
    
                if (rootStaticFiles.contains(requestPath)
                        || requestPath.startsWith(REACT_STATIC_DIR)) {
                    return new ClassPathResource(REACT_DIR + requestPath);
                } else
                    return index;
            }
    
        }
    }
    
    
Its done. Application frontend will run as smooth.