I want to implement this into my Next.js App
https://codepen.io/Lemonzillah/pen/rmQLRm
I tried to add both libraries needed for this to work in the _document.js file and then link the js code in text-slider from /public
<Main />
<NextScript />
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.5.9/slick.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="public/text-Slider.js"></script>
But it ain't working, somehow - it doesn't show any error. It's just now working - hope you can help me!
First of all. It is recommended to not use jquery in react or next js app.
Then if you want to use jquery in next js app you can use next docuemnt..
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx)
return { ...initialProps }
}
render() {
return (
<Html>
<Head>
**Here you can use custom css link or font link like bootstrap cdn
</Head>
<body>
<Main />
<NextScript />
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.5.9/slick.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="public/text-Slider.js"></script>
</Html>
)
}
}
export default MyDocument
You can use now slick by calling slick slider cdns link in script and css. Ans use them. It is recommend to use React slick in next js app
Related
I've been playing around with some libraries and tested out react-text fun. I placed the blotter script in my html file and installed the library. When I test out an effect, I get two rendered elements on my page. Any ideas on how to fix this?
public HTML:
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="https://unpkg.com/blotterjs-fork#0.1.0/build/blotter.min.js"></script>
</body>
component:
import React from 'react'
import { LiquidDistortionText } from 'react-text-fun'
// styles
import { Header, HeroContainer } from './Home.styles'
// components
export default function Home() {
return (
<Header>
<HeroContainer>
<LiquidDistortionText
text="Text"
speed={0.25}
rotation={0.2}
distortX={0}
distortY={0.2}
noiseAmplitude={0.1}
noiseVolatility={1}
/>
</HeroContainer>
</Header>
)
}
rendered webpage
Everything looks correct. You should look at your Header Component and HeroContainer. Maybe you used children twice times.
i need help for integrate frontend ReactJS on my site. currently i avoid to use nodeJS or NPM for implement my reactJS. but i'm using ReactJS CDN. so i not run npm start when develop the reactJS. i just want to use the frontend.
Hope this will understand from the start. so i have a question, how do i able to get another component and place it on single file.
I Created file App.js. I plan that this file will become a centralize for other components.
let me share what i'm doing right now.
here is my file structure
this is my code on index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Buynow Project</title>
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<script type="text/babel" src="buynow/index.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
this is my code on index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js'
ReactDOM.render(<App />, document.getElementById('root'));
this is my code on App.js
import React from 'react';
import Navbar from './components/Navbar.js'
function App(props){
return (
<div>
<Navbar/>
Hello App
</div>
);
}
export default App;
this is my code on Navbar.js
import React from 'react';
function NavBar(props) {
return (
<div>
<Navbar/>
Hi NavBar
</div>
);
}
export default NavBar;
but i got this error, and pointed on file index.js line:1
Uncaught ReferenceError: require is not defined
this is error
I confuse how to solve this. I start with the simple code just for testing if it can work or not.
please help.
https://reactjs.org/docs/react-without-jsx.html
JSX is not a requirement for using React. Using React without JSX is
especially convenient when you don’t want to set up compilation in
your build environment.
So you can't use JSX/TSX directly in your browser (need compilation). Also, you can't use import outside a module (so basically now, you can already use your function components by adding the import of all your files in the index.html).
In my experience I suggest that you use the benefits of JSX / TSX and compile your code with NPM to be more comfortable (everything is way more intuitive with jsx).
In any case, in the link that I have included, you will find how to do the equivalent of JSX with pure javascript. That's what you need. (as you can see in my small snippet)
If you want keep using react from CDN and without compiling, your code, should be something like this:
// For the Snippet i have all of your js here
// But you could just import in your index.html every separate component file you have (without any import/export syntax)
function NavBar(props) {
return React.createElement('span', null,props.title);
}
function App(props){
return React.createElement('span', null, React.createElement(NavBar, {title: 'Header'}, null),
React.createElement('span', null,'Hello App'));
}
ReactDOM.render(React.createElement(App, {}, null), document.getElementById('root'));
<html>
<head>
<meta charset="UTF-8" />
<title>Buynow Project</title>
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</html>
Anyway, as you see, the code is not so readable this way...
EDIT
I made the same snippet on stackblitz with separated files
https://stackblitz.com/edit/web-platform-4ruju9?file=index.html
Ps. Also, don't put NavBar inside NavBar or you'll get a render loop
You have to enable module support in script tag
<script type="text/babel" data-type="module" src="./index.js"></script>
Remove React import statements as they can be directly used.
I would like to use the Aladin Lite app on my React app.
When building a site without React, it is very simple to embed the app in a div by doing:
<!-- include Aladin Lite CSS file in the head section of your page -->
<link rel="stylesheet" href="https://aladin.u-strasbg.fr/AladinLite/api/v2/latest/aladin.min.css" />
<!-- you can skip the following line if your page already integrates the jQuery library -->
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js" charset="utf-8"></script>
<!-- insert this snippet where you want Aladin Lite viewer to appear and after the loading of jQuery -->
<div id="aladin-lite-div" style="width:400px;height:400px;"></div>
<script type="text/javascript" src="https://aladin.u-strasbg.fr/AladinLite/api/v2/latest/aladin.min.js" charset="utf-8"></script>
<script type="text/javascript">
var aladin = A.aladin('#aladin-lite-div', {survey: "P/DSS2/color", fov:60});
</script>
Where you then have an object aladin to use in Javascript.
How would I go about using this app on my React page? It was not built for React and uses jquery.
I need to be able to access its props to change the field of view of the sky which in Javascript is done by:
aladin.setFov(1)
Would this be a good time for React portals?
Thank you.
Create a React component that will render Aladin sky map (so there will be no Aladin anywhere else). Then, you can define and configure aladin inside componentDidMount (if you are using class components) or React.useEffect (if you are using hooks).
Index.html:
...
<head>
<link rel="stylesheet" href="https://aladin.u-strasbg.fr/AladinLite/api/v2/latest/aladin.min.css" />
<!-- you can skip the following line if your page already integrates the jQuery library -->
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js" charset="utf-8"></script>
<!-- insert this snippet where you want Aladin Lite viewer to appear and after the loading of jQuery -->
<script type="text/javascript" src="https://aladin.u-strasbg.fr/AladinLite/api/v2/latest/aladin.min.js" charset="utf-8"></script>
</head>
...
Aladin.jsx:
const Aladin = () => {
React.useEffect(() => {
let aladin = A.aladin('#aladin-lite-div', { survey: 'P/DSS2/color', fov:60 })
aladin.setFov(1)
}, [])
return (
<div id='aladin-lite-div' style={{ width: '400px', height: '400px' }} />
)
}
export default Aladin
Then, everywhere you want to render Aladin sky map:
import Aladin from './Aladin'
...
<Aladin />
Just an update to Michal's answer.
let aladin = window.A.aladin('#aladin-lite-div', { survey: 'P/DSS2/color', fov:60 })
The function A.aladin can't be called straightaway since it is an external JavaScript function.
Im Building a website with Next.Js and I tried to implement an external .js file (Bootstrap.min.js & Popper.min.js) but it is not displayed.
Im not sure what the problem is!
I implemented it like this:
import Head from 'next/head';
//partials
import Nav from './nav'
const Layout = (props) => (
<div>
<Head>
<title>Site</title>
{/* Meta tags */}
<meta charset="utf-8"></meta>
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"></meta>
{/* Standard page css */}
<link rel="stylesheet" type="text/css" href="/static/css/page.css"/>
{/* Bootstrap CSS */}
<link rel="stylesheet" href="/static/includes/bootstrap.min.css"/>
{/* jQuery first, then Popper.js, then Bootstrap JS */}
<script src="/static/includes/popper.min.js"></script>
<script type="text/javascript" src="/static/includes/bootstrap.min.js"></script>
</Head>
<Nav/>
{props.children}
</div>
);
export default Layout;
It looks good to me? what am I missing, it's not projecting as it should!
When I tried a script inside the page it shows "Hello JavaScript" for a very short time and then it disappears?
<p id="demo"></p>
<script>document.getElementById("demo").innerHTML = "Hello JavaScript";</script>
How do i fix it?
Please help!
Im Using:
"next": "^8.0.3",
"react": "^16.8.4",
"react-dom": "^16.8.4"
You need to put all your scripts inside the Head tag.
Don't put raw javascript inside the Head tag. Put it in a separate file and import the script in the Head tag
You can create a .js file, which contains your raw js code, in the public folder and then use the script in the Head tag. I am not sure why we have to do this, but this is how it works in Next.js
So for your problem, this will work:
public/js/myscript.js
document.getElementById("demo").innerHTML = "Hello JavaScript";
Layout.js
import Head from 'next/head';
const Layout = (props) => (
<div>
<Head>
{/* import external javascript */}
<script type="text/javascript" src="..."></script>
<script type="text/javascript" src="/js/myscript.js"></script>
</Head>
<p id="demo"></p>
</div>
);
export default Layout;
You can use Script tag from next/script for importing external .js files.
The following is an example snippet from one of my projects. I had to import the script at the end of the page due to some DOM manipulations so the Script tag worked exceptionally well :)
import Script from "next/script";
import Content from "../components/Content";
import Header from "../components/Header";
const index = () => {
return (
<div>
<Header />
<Content />
<Script type="text/javascript" src="./assets/js/main.js" />
</div>
);
};
export default index;
This is working as Expected for me.
<script
dangerouslySetInnerHTML={{
__html: `
console.log('Console message');
`,
}}
/>
#GunnerFan was in the right path. NextJS recommends putting these files in the public folder
So
import Head from "next/head";
// ... elsewhere in your code
<HEAD>
<script type="text/javascript" src="js/myscript.js"></script>
</HEAD>
You can refer to files in the folder directly, e.g: js/<your file>
Be careful not to name them same as files in the pages directory, i.e
INCORRECT: pages/myscript.js & js/myscript.js
Ref: https://nextjs.org/docs/basic-features/static-file-serving
I'm a total React newbie and I guess there is something fundamental I don't quite understand here. A default Gatsby page looks like this. Is there a way to use a local .js file somewhat like this?
<script src="../script/script.js"></script>
What I would like to achieve is to have react ignore script.js but still have the client side use it. A default Gatsby page looks like this, is it possible to do somerthing like that there?
import React from "react"
import { Link } from "gatsby"
import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"
const IndexPage = () => (
<Layout>
<SEO title="Home" keywords={[`gatsby`, `application`, `react`]} />
<h1>Hi people</h1>
<p>Welcome to your new Gatsby site.</p>
<p>Now go build something great.</p>
<div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
<Image />
</div>
<Link to="/page-2/">Go to page 2</Link>
</Layout>
)
After several hours of frustration I finally stumbled upon discussion on GitHub that solved this for me. In Gatsby, there is a thing called static folder, for which one use case is including a small script outside of the bundled code.
Anyone else in the same situation, try proceeding as follows:
Create a folder static to the root of your project.
Put your script script.js in the folder static.
Include the script in your react dom with react-helmet.
So in the case of the code I posted in my original question, for instance:
import React from "react"
import Helmet from "react-helmet"
import { withPrefix, Link } from "gatsby"
import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"
const IndexPage = () => (
<Layout>
<Helmet>
<script src={withPrefix('script.js')} type="text/javascript" />
</Helmet>
<SEO title="Home" keywords={[`gatsby`, `application`, `react`]} />
<h1>Hi people</h1>
<p>Welcome to your new Gatsby site.</p>
<p>Now go build something great.</p>
<div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
<Image />
</div>
<Link to="/page-2/">Go to page 2</Link>
</Layout>
)
Notice the imports
import Helmet from "react-helmet"
import { withPrefix, Link } from "gatsby"
and the script element.
<Helmet>
<script src={withPrefix('script.js')} type="text/javascript" />
</Helmet>
This would have saved hours of my time, hopefully this does it for someone else.
There are many ways to add scripts in GatsbyJS...
To execute a script on a specific page
create a stateless ScriptComponent.js file and place it inside your /src folder.
in your ScriptComponent.js use require() to execute the script inside useEffect() like this:
const ScriptComponent = ({
src, // if internal,put a path relative to this component
onScriptLoad = () => {}, // cb
appendToHead = false,
timeoutDuration = 10,
defer = false,
isExternal = false,
}) => {
useEffect(() => {
setTimeout(() => {
if (isExternal) {
const script = document.createElement('script');
script.src = src;
script.onload = onScriptLoad;
defer
? script.defer = true
: script.async = true;
appendToHead
? document.head.appendChild(script)
: document.body.appendChild(script);
} else { // for internal scripts
// This runs the script
const myScript = require(src);
}
}, timeoutDuration);
}, []);
return null;
};
To run it on client-side, you could check the window object inside your script.js file if you didn't run it in useEffect:
if(typeof window !== 'undefined' && window.document) {
// Your script here...
}
finally, go to the page you want to execute the script in it (e.g. /pages/myPage.js ), and add the component <ScriptComponent />
If you want to execute a script globally in (every component/page) you could use the html.js file.
first, you'll have to extract the file (in case you didn't) by running:
cp .cache/default-html.js src/html.js
inside your html.js file:
<script dangerouslySetInnerHTML= {{ __html:`
// your script here...
// or you could also reuse the same approach as in useEffect above
`}} />
Just create gatsby-ssr.js file on root folder
and add the following pattern for your scripts folder
import React from 'react'
export const onRenderBody = ({ setPostBodyComponents }) => {
setPostBodyComponents([
<script
key="https://code.jquery.com/jquery-3.2.1.slim.min.js"
src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossOrigin="anonymous"
defer
/>,
<script
key="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossOrigin="anonymous"
defer
/>,
<script
key="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossOrigin="anonymous"
defer
/>
])
}
Then, you at the end of dom you'll see the links to scripts
If you'd like to use a Gatsby plugin, which to me is no different from using an external library like Helmet (plugins are npm packages after all), you could use gatsby-plugin-load-script.
You can provide either the url to the src attribute or a local path. If you're going to store your JS in a local file such as some-minified-js.min.js - make sure to store in the static directory at the root of your project.
Once you do this, you can access via the global object:
global.<object or func name here>
For example, I was trying to include a very small JS library via a minified file, so I stored the file in /static/my-minified-library.min.js and then:
Installed the plugin: npm i --save gatsby-plugin-load-script
Added this to my gatsby-config.js
plugins: [
{
resolve: "gatsby-plugin-load-script",
options: {
src: "/my-minified-library.min.js",
},
},
],
Accessed in my react component like so:
useEffect(() => {
const x = new global.MyImportedLibraryObject();
}, []}
Gatsby uses html.js in the src folder. Not index.html like most react projects.
Example html.js file:
import React from "react"
import PropTypes from "prop-types"
export default class HTML extends React.Component {
render() {
return (
<html {...this.props.htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
{this.props.headComponents}
</head>
<body {...this.props.bodyAttributes}>
{this.props.preBodyComponents}
<div
key={`body`}
id="___gatsby"
dangerouslySetInnerHTML={{ __html: this.props.body }}
/>
{this.props.postBodyComponents}
</body>
</html>
)
}
}
HTML.propTypes = {
htmlAttributes: PropTypes.object,
headComponents: PropTypes.array,
bodyAttributes: PropTypes.object,
preBodyComponents: PropTypes.array,
body: PropTypes.string,
postBodyComponents: PropTypes.array,
}
For adding custom Javascript using dangerouslySetInnerHTML inside src/html.js:
<script
dangerouslySetInnerHTML={{
__html: `
var name = 'world';
console.log('Hello ' + name);
`,
}}
/>
You can try adding your js there but, note that your js may not work as expected. You can always look into react-helmet for more dynamic apps and adding scripts to <head>.
Gatsby Documentation: https://www.gatsbyjs.org/docs/custom-html/
You can do this very easily with the Gatsby plugin "gatsby-plugin-load-script."
Simply do this:
Create a folder named static at the root of your gatsby app
Place your script in it
Add the following configuration in gatsby-config.js
{
resolve: 'gatsby-plugin-load-script',
options: {
src: '/test-script.js', // Change to the script filename
},
},
I'm not sure if anyone still needs this answer, but here it goes:
The answer by Elliot Marques is excellent. If you need it for a local file, upload the script to Github and use a service like JSDelivr. It saves a lot of time and stress.
React works with dynamic DOM. But for rendering it by browser, your web server should send a static index page, where React will be included as another script tag.
So, take a look on your index.html page, which you can find in public folder. There you could insert your script tag in the header section, for example.