Customizing react-datepicker's size and position with styled-components
Today I had to use a DatePicker at work.
The project was set up with babel, so I couldn't use the mui datepicker, and I used the original DatePicker instead.
The problem was that I wanted to make the DatePicker bigger and adjust its position, but that wasn't easy to change.
So after a lot of struggling, I chose to edit the CSS piece by piece.
First, install DatePicker.
npm install react-datepickerTo put it simply, when you click the DatePicker, the popup goes in as the very last child of the parent element the DatePicker belongs to, so applying CSS is easy once you keep this in mind.
import React, { useState } from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { styled } from "styled-components";
export default function DatePickerTest() {
const [startDate, setStartDate] = useState(new Date());
return (
<DateParent>
<DatePicker
selected={startDate}
onChange={(date: Date) => setStartDate(date)}
/>
</DateParent>
);
}
const DateParent = styled.div`
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
position: relative;
.react-datepicker-popper {
transform: translate(345px, 490px) !important;
}
.react-datepicker__triangle {
display: none;
}
`;

One thing to watch out for: you have to apply position: relative to the parent DOM element to be able to adjust the position.
Also, open the developer tools, find the className of the element you want to change, and edit it.
- #CSS
- #DatePicker
- #styled-components
- #Parent Element
- #Resizing
- #Child Element