Adding CSS Support for TypeScript React

Let’s extend the previously build Webpack TypeScript React project to include CSS support. For a small application or widget, it is better to bundle CSS with JavaScript code. This post focuses on getting Bootstrap and styled-jsx working for a React project with TypeScript.

Styled-jsx enables us to inject CSS style as a react component. You can create a react component returns the style tag with inline css. See example here.

(1) Install dependencies

npm i --save bootstrap
npm i --save-dev style-loader css-loader
npm i styled-jsx --save

(2) Update webpack.config

We need to add style-loader and css-loader. The style-loader must be loaded first. Otherwise, you will get an error.

module: {
    rules: [
      { test: /\.tsx?$/, exclude: /node_modules/, loader: "ts-loader"},
      { test: /\.js$/, use: ["source-map-loader"], enforce: "pre" },
      { test: /\.css$/, use: ['style-loader', 'css-loader']}
    ]
  },

(3) Adding bootstrap support

create css folder in the public folder and import with bootstrap.css file first, then import it in index.tsx file where you have ReactDom.render() method. In this way, bootstrap will get compiled into a bundle.

bootstrap.css

@import "../../node_modules/bootstrap/dist/css/bootstrap.css";

index.tsx

import '../public/css/bootstrap.css'

(4) Get styled-jsx work

Styled-jsx takes two attributes in the style element, jsx and global as style jsx global. As TypeScript does not know their types, it complains. To add types for these attributes, we can add the definitions in the custom.d.ts file in the src folder.

Everything should work smoothly now. For more complete example, please check out this repo.

Front-End
TypeScript: type aliases to check type equality

This post is to analyse how the type equality check by using type aliases proposed by Matt Pocock in his twitter post. These type aliases allow us to elegantly express type equality checks in unit tests. All we need to do is to pass the output and expected types in …

Front-End
Fixing it.only type error in Jest

If you are getting a type error with it.only in Jest, it could be due to incorrect TypeScript typings or incompatible versions of Jest and TypeScript. To resolve this issue, you can try the following steps: Make sure you have the latest versions of Jest and its TypeScript typings installed …

Front-End
yup conditional validation example

Here’s an example of a Yup validation logic where the first input field is optional but, if filled, it must contain only alphabetic characters, and the second input field is required: import * as Yup from “yup”; const validationSchema = Yup.object().shape({ firstField: Yup.string().matches(/^[A-Za-z]*$/, { message: “First field must contain only …