Next.js script render - javascript

In my Next.js project I have a script that renders a widget as follows:
<a
className="e-widget no-button xdga generic-loader"
href="https://example"
rel="nofollow"
>
3 lucky winners stand a chance to win…
</a>
<Script
type="text/javascript"
src="https://widget.gleamjs.io/e.js"
strategy="afterInteractive"
></Script>
The problem is that once this script executes on the initial render, it does not execute again later.
Anyone know how I can get the script to execute multiple times?

The issue might be originating from other parts but you can give this a shot:
import React, { FC } from "react";
import Script from "next/script";
interface Props {
id: string;
}
const Widget: FC<Props> = ({ id }) => {
return (
<>
<a
className="e-widget no-button xdga generic-loader"
href="https://example"
rel="nofollow"
>
3 lucky winners stand a chance to win…
</a>
<Script
id={id}
src="https://widget.gleamjs.io/e.js"
strategy="afterInteractive"
/>
</>
);
};
export default Widget;

I managed to solve the problem by forcing the parent component to re-mount, which then causes my Script tag to re execute/render as desired.

Related

Next.js prepending current path for nested dynamic routes in Link components

How would you go about dealing with nested dynamic routes and using Next.js Link component?
Say I have 2 file paths:
/pages/projects/index.js
<Link href={`/projects/${project.id}`} key={index}>
<a>Project Name</a>
</Link>
This will take me to localhost:3000/projects/some-id/
and
/pages/projects/[pid]/index.js
This is where I'm having trouble figuring out how to prepend the path of localhost:3000/projects/some-id/
<Link href={`/${router.pathname}/apple`}>
<a>Business name</a>
</Link>
If I use router.pathname, I get /projects/[pid]/apple, and its missing the domain name, if I use router.asPath, I get the correct path, but its still missing the domain. I don't know if this is the correct way, because i shouldn't be adding the domain name into Link's href.
For a nested dynamic route in Nextjs, you could set up your project like so:
Starting with a simple link in index.js
import Link from 'next/link';
export default function Index() {
return (
<section>
<h2>Index</h2>
<Link href="/projectA">
<a>Project A</a>
</Link>
</section>
);
}
Once you are in [projectId].js use useRouter to get current param and append to your next route
import Link from 'next/link';
import { useRouter } from 'next/router';
export default function Project() {
const router = useRouter();
const { projectId } = router.query;
return (
<section>
<Link href={`/${projectId}/2`}>
<a>Project 2</a>
</Link>
</section>
);
}
Working example

Integrate a Spreadshop site using React

I am building a website using React, and I want to integrate a shop from spreadshop.com / spreadshirt.com, to my React website.
Spreadshop.com gives quite good instructions on how to use script-tags to integrate their shop to an html-site (instructions can be found here).
I am not an experienced programmer, and I'm a little confused about how scripts work with React and especially about where I should put the spread_shop_config, which the Spreadshop instructions tells me to have available in window Scope. I have tried to use a useScript-hook, which I found here. But it doesn't seem to work.
Below is my implementation attempt so far.
What am I doing wrong? How can I integrate the Spreadshirt shop to my React website?
import React from 'react';
import useScript from './Hooks/useScript';
function Shop() {
const [loaded, error] = useScript('https://shop.spreadshirt.no/shopfiles/shopclient/shopclient.nocache.js');
var spread_shop_config = {
shopName: 'awesome-merch-shop',
locale: 'US',
prefix: 'https://shop.spreadshirt.com',
baseId: 'shop'
}
return (
<div className="shopBody">
{loaded && !error && (
<div id="shop">
<div>
<i id="spinner" className="fa fa-spinner" aria-hidden="true"/>
<p>Loading The Shop...</p>
</div>
</div>
)}
</div>
);
}
export default Shop;
I'll answer myself here, since I figured a better way and which actually works (better) for all scripts even if you need to add multiple different scripts to a page/component.
(Now I'm actually confused why we need a useScript-hook at all).
Inside the react component that needs to use the script, it seems better to use javascript to create a script-element and then append it to the document.body.
So in example, to add the Spreadshop.com script inside the Shop-component:
import React from 'react';
import './Shop.css';
function Shop() {
var js = document.createElement("script");
js.type = "text/javascript";
js.src = "https://shop.spreadshirt.no/shopfiles/shopclient/shopclient.nocache.js";
document.body.appendChild(js);
return (
<div className="shopBody">
<div id="shop">
<i id="spinner" className="fa fa-spinner" aria-hidden="true"/>
<p>Loading The Shop...</p>
</div>
</div>
);
}
export default Shop;
And the Spreadshop configurations variable I just add normally with script tags inside the index.html in the publics folder.
<script>
var spread_shop_config = {
shopName: 'awesome-merch-shop',
locale: 'US',
prefix: 'https://shop.spreadshirt.com',
baseId: 'shop'
}
</script>
By doing it this way, the Spreadshop script won't give an error message when loading every component, because the script is only appended when that component loads.
And also, since the script is loaded whenever that component is loaded, it will work even if you refresh the page, while if the script was only in the index.html then the index.html would have to be loaded for the script to be loaded.
Include the javascript and Spreadshirt config in your high-level index.js file. For most it's something like /public/index.html (the same folder you have your manifest.json, robots.txt, etc) along with my google fonts and bootstrap include before </html>
For my implementation I added
<script>
var spread_shop_config = {
shopName: 'YourShopNameHere',
locale: 'us_US',
prefix: 'https://shop.spreadshirt.com',
baseId: 'myShop'
};
</script>
<script type="text/javascript" src="https://shop.spreadshirt.com/shopfiles/shopclient/shopclient.nocache.js"></script>
And then in the React component:
import React from 'react';
import './Shop.css';
type Props = {
testProp: string
};
export const Shop = ({ testProp }: Props) => {
return (
<div id="Shop-Component">
<div id="myShop">
<div>is loading text here...</div>
</div>
</div>
);
};
export default(Shop);

Trying to display text, but no luck. However, I check my console and see empty divs with p tags. App is not breaking

I am in the process of working on a joke app, which I am building from scratch by myself with no tutorial. Right now, there is a component SportsJokesApi, that pulls in the data from a local json folder (SportsJokesData) I created. This is how it is set up:
const SportsJokesData = [
{
id: "1",
question: "What did the baseball glove say to the ball?",
answer: "Catch ya later!"
}
]
export default Sports Jokes Data
On the landing page, when the user selects the Sports Jokes category, they will be taken to a new page which will display jokes related to sports. Right now, you need to click the button (Click here for a joke) in order for the first joke to display. I would love for the first random joke to already be displaying when the user selects this category and gets taken to that page for the first time.
This is how I have the component set up. In my initial approach I created a separate function called getInitialJoke, which returns a random joke. Then in the render, I created a variable called const {initialJoke} which is this.getInitialJoke(); and then the joke would be displayed. Since state update is asynchronous, I did some safety checking by using initialjoke?.answer. When I go back and run the app, no joke appears and the text does not show up. However, I do see new divs with empty p tags on console. Does anyone know what could be wrong and how I can fix this? Again, I want a joke to already be displaying. The way it is set up in this component, you have to click on the Click Here for a Joke button in order to see the first joke.
import React from 'react'
import SportsJokesData from '../data/SportsJokesData';
import { Link } from 'react-router-dom';
import './Buttons.css';
const initialState = {
randomJoke: {}
};
class SportsJokesApi extends React.Component {
constructor(props) {
super(props);
this.getRandomJoke = this.getRandomJoke.bind(this);
this.state = initialState;
}
getInitialJoke() {
return SportsJokesData[(SportsJokesData.length * Math.random()) << 0];
}
getRandomJoke() {
this.setState({
randomJoke: SportsJokesData[(SportsJokesData.length * Math.random()) << 0]
});
}
render() {
const {randomJoke} = this.state;
const {initialJoke} = this.getInitialJoke();
return (
<React.Fragment >
<div>
<p>{initialJoke?.question}</p>
</div>
<div>
<p>{initialJoke?.answer}</p>
</div>
<div className="flex">
<p>{randomJoke.question}</p>
</div>
<div className="flex">
<p>{randomJoke.answer}</p>
</div>
<div className="flex">
<button class="btn joke" onClick = {this.getRandomJoke}>Click here for joke </button>
</div>
<div className="flex">
<Link to="/ProgrammingJokes">
<button className="btn programming">Programming Jokes</button>
</Link>
</div>
<div className="flex">
<Link to="/DadJokes">
<button className="btn dad">Dad Jokes</button>
</Link>
</div>
<div className="flex">
<Link to="/SpanishJokes">
<button className="btn spanish">Chistes en ñ</button>
</Link>
</div>
<div className="flex">
<Link to="/">
<button className="btn home">Home Page</button>
</Link>
</div>
</React.Fragment >
);
}
}
export default SportsJokesApi;
Perhaps you could call the initialJoke() function in one of the React lifeCycle Events, for example with something like this:
// Add this to your code fellow.
componentDidMount() {
this.getInitialJoke();
}
For more information on the life cycle events and how they work, have a look at this great article, buddy.
React: Component Lifecycle Events

How to make a Dynamic dropdown done in React with SQL database

I'm building a react app using facebook's:
https://github.com/facebookincubator/create-react-app
I´m new to react and I havent done a dropdown menu before. I have read a lot in the web and I figure I maybe need to use the select and options tags?
I want to have 4 image buttons as I call Main menu (three of the buttons will be able to navigate directly to the picked page).
The last image button will show an undermenu with 12 options pages to go to.
Option Option Option Option
Undermenu
12 options
I´m unsure where I shall begin, right now I have done some coding before I knew I needed to connect it to the SQL database.
App.js:
import React, { Component } from 'react';
import './sass/style.scss';
import Admin from "./components/routes/Admin";
import DropdownMenu from "./components/DropdownMenu";
class App extends Component {
render() {
return (
<div className="App">
<Admin />
<DropdownMenu />
<p className="TEST"> lorem imsum </p>
</div>
);
}
}
export default App;
DropdownMenu.js component:
import React from 'react';
import main_menu_home from '../images/Buttons/main_menu_home.png';
import main_menu_dragons from '../images/Buttons/main_menu_dragons.png';
import main_menu_dragon_test from '../images/Buttons/main_menu_dragon_test.png';
import main_menu_fortune_cookie from '../images/Buttons/main_menu_fortune_cookie.png';
const DropdownMenu = props => (
<header>
<nav>
<div className="dragonMenu-container">
<div className="dragonMenu">
<ul>
<li>
<img
id="Home"
className="Main_home"
src={main_menu_home}
alt="Home_button_image"
/>
</li>
<li>
<img
id="Dragons"
className="Main_Dragons"
src={main_menu_dragons}
alt="Dragons_button_image"
/>
</li>
<li>
<img
id="Dragon_test"
className="Main_Dragon_test"
src={main_menu_dragon_test}
alt="Dragon_test_button_image"
/>
</li>
<li>
<img
id="Fortune_cookie"
className="Main_fortune_cookie"
src={main_menu_fortune_cookie}
alt="Fortune_cookie_button_image"
/>
</li>
</ul>
</div>
</div>
</nav>
</header>
);
export default DropdownMenu;
Here the code just display four images which it gets from the images/Buttons folder. Maybe you don´t need so many imports and can get all the images with just a proper link to the image but I donno how to.
I think I need a global variable that pointing where all my images are so I can just have to invoke said variable to access the folder where the pictures are.
Ideas?
But back to the Dropdown problem:
I guess I need to create a table in my Sql?
But I donno how.
My problem is that I think of all things at the same time I need to do, but can´t easy myself to do one thing at the time.
I have more code for when I before fetched all from another table if you want to see that code as well.
Any questions, feel free to ask away :)
// Dragoness
UPDATED 18 sep 2019:
Right now, I have come this far:
I can now talk to the SQL database with react and print out some data from the SQL database itself. My problem now is that I just see broken images, does anyone have a solution for my problem?
What I see on the browser
My SQL database menus table with 4 columns
What I wrote in the browse tag to enter my data
Where I have MainMenu.js file and where I want the Buttons images from
App.js:
import React, { Component } from 'react';
import './sass/style.scss';
import Admin from "./components/routes/Admin";
import DropdownMenu from "./components/DropdownMenu";
import MainMenu from "./components/MainMenu";
class App extends Component {
render() {
return (
<div className="App">
<Admin />
<DropdownMenu />
<MainMenu />
<p className="TEST"> lorem imsum </p>
<div><img src='./images/Buttons/main_menu_home.png'/> </div>
</div>
);
}
}
export default App;
fetchMenu.php:
<?php
/* This file fetches current menus . */
include_once 'database.php';
$statement = $pdo->prepare("SELECT * FROM menus ORDER BY picUrl ASC");
$statement->execute();
$data = $statement->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($data, JSON_PRETTY_PRINT);
?>
MainMenu.js:
import React, { Component } from 'react';
import "../App.scss";
class DropDownMenu {
id: 0;
picUrl: "";
linkUrl: "";
isSubmenu: "";
}
class MainMenu extends Component {
constructor(props) {
super(props);
this.state = {
allMenus: []
}
}
fetchAllMenus = () => {
fetch("http://localhost/dragonology/server/fetchMenu.php")
.then(response => response.json())
.then(data => {
console.log(data);
this.setState({ allMenus: data });
});
}
componentDidMount() {
this.fetchAllMenus();
}
render() {
let menu = this.state.allMenus.map((item) => {
return (<div key={item.id}><img src={item.picUrl} alt="dropdownmenu_main_and_under"/> - {item.linkUrl} - {item.isSubmenu}</div>)
});
console.log(menu);
return (
<div>{menu}</div>
);
}
}
export default MainMenu;
Thank you in advance
// Dragoness
Updated 19 sep 2019 with solution
I got some tips from those links:
I changed my images folder to be in the public instead of in src:
getting broken image in React App
Started to see a pattern that most of the tables with an image inside have some kind of "name" column, at least it worked for me:
https://www.youtube.com/watch?v=lTyks6s6b6E
All my success steps I took:
Fixed:
1. I added a folder called images inside the public folder.
2. Added one image of the main menu that I called home.
3. Went to the SQL database, deleted the old rows I tried to display the
data from that you can see on the browse tab that was inside the table
menus.
4. Added another column called picName. Took it as a varchar with 60 in
lengh.
5. Changed the settings on the picUrl to be a varchar with the lengh of
255 instead of 100 that I had before.
6. I did a test using the insert tab selection to add a row with the image
link I had before with the dot dot slash and it worked!.
7. Added 15 more rows(all main and undermenu buttons with its data).
8. After that I changed the folder structure again to have images/Buttons
and added all the button images that I had inside the src folder before.
9. Deleted all the images that were on the old folder.
10. Fixed: App.js took away the import of the DropDownMenu.js component and that it didnt print out my DropDownMenu.js component anymore.
App.js:
import React, { Component } from 'react';
import './sass/style.scss';
import Admin from "./components/routes/Admin";
import MainMenu from "./components/MainMenu";
class App extends Component {
render() {
return (
<div className="App">
<Admin />
<MainMenu />
<p className="TEST"> lorem imsum </p>
<div><img src='./images/Buttons/main_menu_home.png'/> </div>
</div>
);
}
}
export default App;
I couldn´t add the images of how my SQL database look now instead of before/where I find my images now in what folder because am new in Stack Overflow and don´t have enough reputation apperely. But those above are the steps I took to solve my problem :)

How to display the params on the web (React Js)

I have the following js
App.js
<LayoutRoute
exact
path="/analysis/:id"
layout={MainLayout}
component={AnalysisPage}
/>
index.js
<IconWidget
title="companyA"
subtitle="Top Product Trade: Pen"
color="info"
onClick={()=>{window.location='analysis/companyA'}}
/>
analysis.js
function analysisPage({match}){
console.log(match)
return(
<div>
{"${match.params.id}"}
</div>
)
}
const AnalysisPage= () => {
return(
<div>
Company: {this.analysisPage}
</div>
export default AnalysisPage;
I have applied react router in the App.js which can redirect the website from index.js to analysis.js by pressing the button.
However, I would like to display the params to the div. I took reference from https://alligator.io/react/react-router-parameters however, it doesn't work. I would like to know what have I did wrong? Thank you so much
You have to provide the props:
Company: {this.analysisPage(this.props)}
So that match params could be used:
function analysisPage({match}){
You can try this
this.props.match.params.id

Categories