Prem
Prem

Reputation: 5997

Issue with loading react-datepicker css into jsx file

As per the react-datepicker documentation, I tried importing the css file, but react throws an error as You may need an appropriate loader to handle this file type. I have included the css-loader in webpack-config file. Is there anything missing? The following is the import part of jsx file

import React, { Component } from 'react';
import moment from 'moment';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

Following is the webpack.config.js

const Notifier = require('webpack-build-notifier');
const path = require('path');

const plugins = [new Notifier({ title: 'Webpack' })];
const output = path.join(__dirname, 'public', 'javascripts');

const babelConfig = {
  presets: [
    ['@babel/preset-env', {
      useBuiltIns: 'usage',
      targets: {
        browsers: [
          'last 2 versions',
          'ie >= 11',
        ],
      },
    }],
    '@babel/react',
  ],
};

const cssConfig = [
    { loader: 'style-loader' },
    { loader: 'css-loader', options: { importLoaders: 1 } },
    { loader: 'postcss-loader' },
];

const sassConfig = [
  { loader: 'style-loader' },
  { loader: 'css-loader', options: { importLoaders: 1 } },
  { loader: 'postcss-loader' },
  { loader: 'sass-loader' },
];

module.exports = {
  entry: { bundle: ['./src/client/router.jsx'] },
  output: { filename: '[name].js', path: output },
  devtool: 'source-map',
  resolve: { extensions: ['.js', '.jsx', '.json', '.css', '.scss'] },
  module: {
    rules: [
      {
        test: /\.css$/,
        exclude: /node_modules/,
        use: cssConfig,
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        use: sassConfig,
      },
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: babelConfig,
      },
    ],
  },
  plugins,
};

Upvotes: 3

Views: 2557

Answers (3)

Cris R
Cris R

Reputation: 1398

In my case, when using react_rails, I had to import the file in the scss that corresponds to the main React component I was mounting (app/assets/stylesheets/index.scss).

@import "react-datepicker/dist/react-datepicker";

Upvotes: 1

Alan Kuper
Alan Kuper

Reputation: 26

import DatePicker from "react-datepicker"
require('react-datepicker/dist/react-datepicker.css')

it should work

Upvotes: 0

Prem
Prem

Reputation: 5997

The issue is the react-datepicker itself is a node-module which itself contains css files. I made it working by manually copying and pasting those css files somewhere within the project location except the nodu_modules folder (as this is excluded by webpack config)

Upvotes: 0

Related Questions