I want to use bootstrap class and next.js modules together inline - reactjs

I want to use bootstrap classes and my definitons in next.js modules together. How can I do it?

First, rename your .header-top to .headerTop in header.module.scss.
Then, include your class name:
<div className={`${styles.headerTop} container d-flex ...`}>
Explanation: class names in CSS modules are automatically processed to make them unique to ensure scoping. For example, .headerTop will become something like .header_headerTop__JnCx9 (.fileName_className_randomString). Therefore, in components you need to include your class names as JavaScript expressions rather than strings. Namely, if you would have one class name, you would do: <div className={styles.headerTop}></div>. But in your case you want to include your own class name with bootstrap classes (which are not CSS modules). One way of doing it is using Template literals which allow to include expressions within strings.

You need to first install bootstrap.
npm install --save bootstrap
You can only import css in one location in NextJS.
create pages/_app.js and import the css file.
import 'bootstrap/dist/css/bootstrap.min.css';

in pages/_app.js
Head Tag and insert ALL bootstrap into it:
<Head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"></link>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script>
</Head>
Then in any component, once you have imported your Name.module.css, e.g.:
import styles from '../styles/Navbar.module.css';
Now you can combine self-made CSS classes with Bootstrap classes like this:
<div className={`${styles.redBorder} bg-dark`}></div>
NOTE: you CAN NOT use dashes for class names, so this will NOT work:
.red-border;
this will NOT apply in next.js
instead use CamelCase.
.redBorder;
then it works.

Related

How to use node module in Kotlin React?

I'm trying to use the bootstrap library. To do so, my first guess was to do the same as the Kotlin React tutorial :
I managed to import the bootstrap library using npm import easily but then I struggle to actually use it and in particular to add arguments. As shown in the example:
#file:JsModule("react-bootstrap")
#file:JsNonModule
import react.*
#JsName("Button")
external val ReactButton: ComponentClass<ReactButtonProps>
external interface ReactButtonProps : Props {
var variant: String
var size: String
}
Which indeed creates a button when used :
ReactButton {
variant="primary"
size = "lg"
+"Exemple"
}
But the color and size aren't changing whatever argument I put.
Then I tried to proceed like another topic on Stack Overflow: How to import node module in React-Kotlin?
But I don't understand what RProps are and RClass and I can't seem to use them.
My goal is to use a dropdown from Bootstrap but I thought trying with button first would have been easier. How do I make the button customizable?
Add this to your head tag in your index.html folder
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous" />
make sure you have implementation(npm("react-bootstrap","2.4.0")) in your build.gradle.kts within your js dependencies

How can one have a theme switcher in primereact

I would like to be in a position to switch between themes in primereact rather than import one theme and then it affects my whole app and I don't have an option to switch between dark or light mode.
Observing how they do it on the website www.primefaces.org/primereact/showcase/, open Developer view: Elements, and one can notice that choosing a different theme changes css file link in HTML header:
<link id="theme-link" rel="stylesheet" href="./themes/bootstrap4-light-blue/theme.css">
becomes
<link id="theme-link" rel="stylesheet" href="./themes/bootstrap4-light-purple/theme.css">
It is fairly easy to switch link element HREF from one to another.
This page talks about primereact theme switching:
Switch Your React App Between Material, Bootstrap and Custom Themes at Runtime
But the method it describes is too convoluted, involves ejecting and custom webpack, to bundle all theme CSS files and import them programmatically, like that:
const changeTheme = (theme) => {
import(`./${theme}.scss`).then((module) => {
if (selectedThemeModule) {
selectedThemeModule.unuse();
}
module.use();
setSelectedThemeModule(module);
});
}
Instead, grab the example repo where they do method of link HREF swap: github.com/mertsincan/primereact-dynamic-theming/
example-1 has code for the convoluted method from the above page, you can skip it and go to example-2, which is much simpler.
In a nutshell, add to 'public/index.html', in <header> section:
<link id="app-theme" rel="stylesheet" type="text/css" href="saga-blue.css">
And use this function:
const changeTheme = (theme) => {
let themeLink = document.getElementById('app-theme');
if (themeLink) {
themeLink.href = theme + '.css';
}
}
Then just call changeTheme(XXX) when theme XXX is clicked.
Next put .css files into the right place - just copy all node_modules/primereact/themes/*/theme.css files into public folder (giving them corresponding theme names). Some theme.css reference fonts - search for "url" in each file, and if present, copy corresponding fonts/ directory too.
I should mention that benefits of example-1 is using minified and bundled CSS files, so themes will be switching faster. If that's important, then follow the above linked tutorial and example-1. Also note that example-2 has very similar setup to example-1 (eject and custom webpack config), but only to copy css files to the right output folder, which can be skipped in favor of copying files by hand once.

Why is the content of my js file replaced by html code?

I am trying to use functions in dcsubscriber.js:
However, when running the website, the content of dcsubscriber.js is replaced completely by some odd html code:
Update:
I use Admin panel to add html code from Markdown editor
You can use react-helmet
Put your js file inside static folder and use them like this :
<Helmet>
<script crossorigin="anonymous" src="/test.js" />
</Helmet>

How can we import js file variable in css file

I have tried to to that using this line of code but it doesn't work
#import url("Javascriptfile.js");
and <script type="text/javascript" src="Script.js">
these two ways doesn't work.
in js file I have
export const PrimaryColor = "#4267B2";
and I want to import it in my css file how can i do it?
I do not believe this is possible in any way.
You can manipulate CSS with JavaScript to a certain extent, but it is mostly done through DOM manipulation (acting on class names) or generating CSS programmatically (but it is still CSS in the end).
I don't think it is ever possible to access "JavaScript world" from the scope of CSS.
However, if you want to use variable names in CSS to reference constants, like colors, sizes, etc., you can use the CSS custom properties feature : https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties

How to get minified files in project ( Gatsby / React )

gatsby version = 2.0.0-beta.19
node version = v10.6.0
npm version = 6.1.0
VScode version = 1.25.1
When adding minified files (.min.js or .js with minified content) to my react Gatsby project, I get the following error when I try to do gatsby develop:
ERROR Failed to compile with 1 errors 10:41:47 AM
error in ./src/components/appinsights.js
Module Error (from ./node_modules/eslint-loader/index.js):
/mnt/d/my_site/src/components/appinsights.js
2:185 error Expected an assignment or function call and instead saw an expression no-unused-expressions
2:248 warning Unexpected use of comma operator no-sequences
2:493 warning Unexpected use of comma operator no-sequences
2:649 error Expected an assignment or function call and instead saw an expression no-unused-expressions
2:660 warning Unexpected use of comma operator no-sequences
2:761 warning Unexpected use of comma operator no-sequences
7:1 error Expected an assignment or function call and instead saw an expression no-unused-expressions
7:31 warning Unexpected use of comma operator no-sequences
✖ 8 problems (3 errors, 5 warnings)
I added a new file "./src/components/appinsights.js" and the contents of the file are from inside the script tag of App insights JS snippet
var appInsights=window.appInsights||function(a){
function b(a){c[a]=function(){var b=arguments;c.queue.push(function(){c[a].apply(c,b)})}}var c={config:a},d=document,e=window;setTimeout(function(){var b=d.createElement("script");b.src=a.url||"https://az416426.vo.msecnd.net/scripts/a/ai.0.js",d.getElementsByTagName("script")[0].parentNode.appendChild(b)});try{c.cookie=d.cookie}catch(a){}c.queue=[];for(var f=["Event","Exception","Metric","PageView","Trace","Dependency"];f.length;)b("track"+f.pop());if(b("setAuthenticatedUserContext"),b("clearAuthenticatedUserContext"),b("startTrackEvent"),b("stopTrackEvent"),b("startTrackPage"),b("stopTrackPage"),b("flush"),!a.disableExceptionTracking){f="onerror",b("_"+f);var g=e[f];e[f]=function(a,b,d,e,h){var i=g&&g(a,b,d,e,h);return!0!==i&&c["_"+f](a,b,d,e,h),i}}return c
}({
instrumentationKey: "<my_key>"
});
window.appInsights=appInsights,appInsights.queue&&0===appInsights.queue.length&&appInsights.trackPageView();
In my "./src/components/layout.js"
import appinsightsFile from './appinsights.js'
...
<Helmet
title={data.site.siteMetadata.title}>
<html lang="en" />
<script type="application/ld+json">{appinsightsFile}</script>
</Helmet>
...
I am not sure if this is a react issue or Gatsby. I can't seem to get any minified code to work with my application.
I have tried:
inline app insights code in my layout.js
taking the script tags out of the helmet code
I am not that experienced and wanted to comment on this, but I need 50 reputation. Anyways, maybe we can solve your issue together.
First off, why do you use type application/ld+json instead of text/javascript as stated in the ApplicationInsights-JS readme?
To debug this issue try to insert the contents of appinsights.js directly into the script tag.
The following should work:
<Helmet
title={data.site.siteMetadata.title}>
<html lang="en" />
<script type="text/javascript">
{`SCRIPT`}
</script>
</Helmet>
If not, try dangerouslySetInnerHTML instead.
Note the back ticks inside {}. If this is working correctly, proceed with your component.
As I know – correct me if I go wrong – the use case of directly importing a file in Gatsby belongs to static files. You could simply import logo from './Logo.svg' and this will return the url to that file. Behind the scenes, Webpack will include that file in the bundle and you can reference it like in src and href attributes.
If you want to include that JavaScript string from a component (that what you placed inside the components directory is not a component), you should write a component for that, which renders this JavaScript.
I didn't try that myself, but I think this could work with some modification.
The errors you are facing are part of eslint, I think. The compiler (Webpack?) expects non-minified ES6 JavaScript. Again, correct me if I am wrong.
Some sort of a stateless functional component should help you here:
appinsights.js
import React from 'react'
const AppInsights = () => {
return `
SCRIPT
`
}
export default AppInsights
layout.js
import AppInsights from './appinsights.js' // Replace with your path.
<Helmet
title={data.site.siteMetadata.title}>
<html lang="en" />
<script type="text/javascript"><AppInsights /></script>
</Helmet>
But I think it is safer to work with dangerouslySetInnerHTML as before.
https://www.gatsbyjs.org/docs/adding-images-fonts-files/
If you put a file into the static folder, it will not be processed by Webpack. Instead it will be copied into the public folder untouched.
You create a folder as your_gatsby_project_folder/static (not in project/src), and put your minified files from outside in it. Whatever is in the static will be copied onto public folder so you can link to them as usual
// in your react file, you can use script tag to link to the minified files
render(){
return(
<div>
<script src="/path/to/your/min.js" />
whatever
</div>
)
}
If you want to take a minified javascript file and add it to a <script tag in the <head of your Gatsby site, you do not want to import it.
Check the docs on custom html.
You could put the file into the static/ folder, then it will be copied into your built output. Then cp .cache/default-html.js src/html.js and edit src/html.js to add the <script tag you want.
However, this is not a very good approach. You would be better to give Gatsby the unminified file if you can. Then you can import it in the normal Gatsby way, and Gatsby will handle minifying it. Gatsby is really good at figuring out what javascript is required where. It's part of why Gatsby sites are so insanely fast. You will lose some of that advantage if you use the approach above.

Resources