Categories
React Answers

How to fix window is not being exposed to Jest?

To fix window is not being exposed to Jest, we create the window object with jsdom.DOM().

For instance, we write

global.window = new jsdom.JSDOM().window;
global.document = window.document;

to create the window object with jsdom.JSDOM().window.

Then we get the document object with window.document.

Categories
React Answers

How to pass an event object to enzyme .simulate?

To pass an event object to enzyme .simulate, we call simulate with a 2nd argument.

For instance, we write

const mockedEvent = { target: {} };
checkbox.find("input").simulate("click", mockedEvent);

to call simulate with the event object as the 2nd argument

Categories
React Answers

How to check the type of a React component?

To check the type of a React component,. we can use the type property.

For instance, we write

import MyComponent from "./MyComponent";

//...

this.props.children.forEach((child) => {
  if (child.type === MyComponent) {
    console.log("This child is <MyComponent />");
  }
});

to check the type property of each child in the children prop to see if it’s MyComponent.

If it is, then the child is a MyComponent instance.

Categories
React Answers

How to turn an SVG string into an image in a React component?

To turn an SVG string into an image in a React component, we just put the SVG code in a base64 URL string and set that as the value of the src prop of the img element.

For instance, we write

class SomeComponent extends React.Component {
  render() {
    const image =
      '<svg xmlns="http://www.w3.org/2000/svg" version="1.2" baseProfile="tiny" width="47.4" height="40.65" viewBox="21 18.5 158 135.5"><path d="M25,50 l150,0 0,100 -150,0 z" stroke-width="4" stroke="black" fill="rgb(128,224,255)" fill-opacity="1" ></path><path d="M25,50 L175,150 M25,150 L175,50" stroke-width="4" stroke="black" fill="black" ></path><g transform="translate(0,0)" stroke-width="4" stroke="black" fill="none" ><circle cx="100" cy="30" r="7.5" fill="black" ></circle><circle cx="70" cy="30" r="7.5" fill="black" ></circle><circle cx="130" cy="30" r="7.5" fill="black" ></circle></g></svg>';
    return (
      <div>
        <img src={`data:image/svg+xml;utf8,${image}`} />
      </div>
    );
  }
}

to put image into the base64 template string.

Then we use the base64 string as the value of the img element src prop.

Categories
React Answers

How to add type of the parameter for onKeyPress with TypeScript and React ?

To add type of the parameter for onKeyPress with TypeScript and React, we set the type of the event object to React.KeyboardEvent<FormControl>.

For instance, we write

const handleKeywordKeyPress = (e: React.KeyboardEvent<FormControl>) => {
  if (e.key === "Enter") {
    if (isFormValid()) {
      handleCreateClicked();
    }
  }
};

to set the e parameter to the React.KeyboardEvent<FormControl> type.

Then we can use e.key to check which key is pressed.