I'm using Tailwind and React, now I need to set font size dynamically from API.
tailwind.config code:
plugins: [
plugin(function({ addBase }) {
addBase({
'html' : {fontSize:"10px"} //this font size should come from API
})
})
],
API response:
{fontSize:"14px",fontFamily:'poppins'}
How can I make fontSize dynamically?
You can achieve this by using CSS variables and manually setting that variable using JS once the response is received from the server.
CSS variables are set on the document (HTML) object itself, so we can easily change it using JS later by accessing the style object like so:
document.documentElement.style.setProperty("--variable-name", value);
tailwind.config.js
set the fontSize
to a CSS variable instead.// tailwind.config.js
plugins: [
plugin(function({ addBase }) {
addBase({
'html' : {fontSize:"var(--html-font-size)"} //this font size should come from API
})
})
],
--html-font-size
variable like so:// script.js
// call your API
async function getFontSizeFromServer() {
try {
const req = await fetch("url");
const res = req.json();
// if you got a successful response from your API
if(req.status === 200 && res) {
document.documentElement.style.setProperty("--html-font-size", res.fontSize)
}
}
catch(err){}
}
You can do something similar for the fontFamily
if you want by creating another variable and setting that as well.