INTRO ๐
Hello World! ๐
Today we are discussing another custom hook๐ช named useFluidFont
๐ฅ. In this post, we will discuss this hook usage, code and use case.
USAGE ๐
As a front-end developer ๐, I know responsive designs
are crucial in web development. Changing font size based on screen size is the main important thing in responsive design. Usually, we use media queries in CSS ๐จ
to achieve this. However, it leads to lengthy code and multiple media queries for different screen sizes ๐. But, by using the useFluidFont
๐ฅ custom hook, we can achieve the same output with efficient code practice ๐.
WITH MEDIA QUERIES ๐
.container {
font-size: 24px;
}
@media screen and (max-width:1280px) {
.container {
font-size: 22px;
}
}
@media screen and (max-width:1140px) {
.container {
font-size: 20px;
}
}
@media screen and (max-width:980px) {
.container {
font-size: 18px;
}
}
@media screen and (max-width:720px) {
.container {
font-size: 16px;
}
}
WITH CUSTOM HOOK ๐
๐ NOTE: before creating this hook, we need to create another hook named
useWinowResize
๐. It is already created on our custom hook series. Please check ๐๐ป useWindowResize
import { useCallback } from "react";
import { useWindowResize } from "./useWindowResize";
export const useFluidFont = () => {
const { width } = useWindowSize();
const getFont = useCallback(
(minFont, minWidth, maxFont, maxWidth) => {
if (width <= minWidth) {
return minFont;
} else if (width >= maxWidth) {
return maxFont;
} else {
return `calc(${minFont}px + (${maxFont} - ${minFont}) * ((100vw - ${minWidth}px) / (${maxWidth} - ${minWidth})))`;
}
},
[width]
);
return getFont;
};
USE CASE ๐
import React from "react";
import "./styles.css";
import { useFluidFont } from "./useFluidFont";
function App() {
const font = useFluidFont();
return (
<div>
<div className="container">HELLO WORLD</div>
<div style={{ fontSize: font(16, 720, 24, 1280) }}>HELLO WORLD</div>
</div>
);
}
export default App;
CONCLUSION ๐
By using the above hook, we can change the font size of application responsively without using multiple CSS media queries.
I hope you people like the useFluidFont hook. We will meet with another hook in another post.
Peace ๐
Top comments (0)