Categories
React Answers

How to access ‘this.props.match.params’ along with other props with React Router?

To access ‘this.props.match.params’ along with other props with React Router, we pass in the matchProps from the render prop function into our component.

For instance, we write

<Route
  path="/champions/:id"
  render={(matchProps) => (
    <ChampionDetails
      {...matchProps}
      {...this.props}
      handleMatch={this.handleMatch}
    />
  )}
/>

to add the Route component and pass in matchProps to the ChampionDetails component.

Now ChampionDetails has access to all the properties of matchProps as props.

Categories
React Answers

How to fix ‘Each child in an array or iterator should have a unique “key” prop’ with React?

To fix ‘Each child in an array or iterator should have a unique "key" prop’ with React, we add the key prop to the items being rendered with map.

For instance, we write

<div className="container">
  {myarray.map((element, index) => {
    return <div key={"mykey" + index}>{element}</div>;
  })}
</div>;

to call map with a function that renders divs.

We add the key prop to the div so React can identify each component being rendered.

Categories
React Answers

How to mock React useRef or a function inside a functional component with enzyme and Jest?

To mock React useRef or a function inside a functional component with enzyme and Jest, we can mock the react module by mocking the useRef hook and getting the rest of the mocked module from the real module.

For instance, we write

import React, { useRef } from "react";
import { shallow } from "enzyme";
import Child2 from "./";

jest.mock("react", () => {
  const originReact = jest.requireActual("react");
  const mUseRef = jest.fn();
  return {
    ...originReact,
    useRef: mUseRef,
  };
});

describe("test", () => {
  it("should pass", () => {
    const mRef = { current: { offsetWidth: 100 } };
    useRef.mockReturnValueOnce(mRef);
    const wrapper = shallow(<Child2></Child2>);
    expect(wrapper.find("#myDiv").text()).toBe("123");
    expect(wrapper.find("p").text()).toBe("Div width is: 100");
  });
});

to mock the react module with jest.mock.

Then we call jest.requireActual to get the real react module.

We call mock with a function that returns the real react module except for the useRef hook which we set to a mocked function.

Then in our test, we call useRef.mockReturnValueOnce to return mRef as the mocked value and then run the rest of our test code.

Categories
React Answers

How to get page URL or hostname in Next.js project?

To get page URL or hostname in Next.js project, we can use next-absolute-url.

For instance, we write

import absoluteUrl from "next-absolute-url";
const { origin } = absoluteUrl(req);
const apiURL = `${origin}/api/job.js`;

to call absoluteUrl with req and then get the hostname from the origin property of the returned object.

Categories
React Answers

How to prevent e and dot in an input type number with React?

To prevent e and dot in an input type number with React, we can validate the input value in the onChange prop function.

For instance, we write

const C = () => {
  //...
  const [val, setVal] = useState("");
  return (
    <div className="App">
      <input
        type="text"
        value={val}
        onChange={(e) => setVal(e.target.value.replace(/[^0-9]/g, ""))}
      />
    </div>
  );
};

to set the onChange prop to a function that replaces non number values with empty strings before call setVal with the string returned by replace that removes all the non digit characters in the input value.

Then we set value to val to show the input value without non digit characters.