Categories
React Answers

How to target child element styled components with React?

To target child element styled components with React, we add & before our selectors.

For instance, we write

const ImgGrid = styled.div`
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  & ${ImgCell}:nth-child(2) ${ColorBox} {
    background: #ff00ff;
  }
`;

to seelct the 2nd child of an element with

& ${ImgCell}:nth-child(2) ${ColorBox}

where ImgCell is a selector that has the 2nd child of the element we’re selecting.

Categories
React Answers

How to import bootstrap .js and .css files with Webpack?

To import bootstrap .js and .css files with Webpack, we add it the paths to resolve the files into the Webpack config.

To do this, we write

module.exports = {
  resolve: {
    alias: {
      jquery: path.join(
        __dirname,
        "development/bower_components/jquery/jquery"
      ),
    },
    root: srcPath,
    extensions: ["", ".js", ".css"],
    modulesDirectories: [
      "node_modules",
      srcPath,
      commonStylePath,
      bootstrapPath,
    ],
  },
};

to make Webpack resolve the directories in the modulesDirectories array.

And we include the extensions of the files to resolve in the extensions array.

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.