Alert is getting triggered automatically in react - javascript

I am new to reactjs, I have been trying to design a UI such that o every click it displays alert telling this li element is clicked but when the page is rendered I see lot of alerts getting popped out. Can someone point out mistake in my code and how to avoid it!
Here is the code snippet
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- <meta name="theme-color" content="#000000" /> -->
<meta
name="description"
content="Web site created using create-react-app"
/>
<title>Grade Score</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
App.js
import './App.css';
function clickhandle (props) {
alert("you clicked on" + props.name)
}
function Stud(props) {
return <li onClick={clickhandle(props)}> { props.name }</li>;
}
function App() {
const students = ['Anil', 'Bob' , 'Clara', 'Dew', 'John', 'Ravi', 'Ram'];
return (
<>
<ul>
{students.map((student) => <Stud name={student} />)}
</ul>
</>
);
}
I want the alerts to be displayed only if I click on the li element but in my my code it continuously pops up alert as soon as page loads!

That's because you are calling the function when the page loads. You have to pass a function to onClick, not call the function directly:
onClick={() => clickhandle(props)}

Related

How to render <scipt> tags in React JS?

I am trying to render <script> tags but unable to do so. Although javascipt is already enabled for the browser. Screenshot of the error message on browser console.
Code snippet.
import './App.css';
import React from "react";
import {Helmet} from "react-helmet";
class App extends React.Component {
render () {
return (
<div className="application">
<h1>My name is </h1>
<script src="https://XXXXX.com/XX.js" id="XXX-embedded-form" primary-color="" secondary-color="" margin-x="" data-uuid="ffwesfwef" ></script>
<Helmet>
<script src="https://XXXXX.com/XX.js" id="XXX-embedded-form" primary-color="" secondary-color="" margin-x="" data-uuid="wefewfwefwe" ></script>
<meta charSet="utf-8" />
<title>My Title</title>
<link rel="canonical" href="http://myurl.net/example" />
</Helmet>
</div>
);
}
};
export default App;

How to start an application dynamically with second.html in Vue3?

I'm developing a vue3 project.
main.js;
import { createApp } from "vue";
import App from "./App.vue";
const app = createApp(App);
import store from "./store";
app.use(store);
import router from "./router/index";
app.use(router);
...
//just try...
app.mount("#app");
and my public/index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title><%= htmlWebpackPlugin.options.title %></title>
<style>
body {
margin: 0px;
}
</style>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
And my App.vue;
<template>
<button #click=openNewPage()>create new page</button>
<span>{{message}}</span>
<router-view />
</template>
<script>
methods:{
openNewPage(){
var t = window.open('second.html','newMonitor','height=700,width=700,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes');
}
}
</script>
my store object;
export default createStore({
state: {
message:'Hello'
}
});
and my second.html;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Cache-Control" content="no-store" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<title></title>
</head>
<body>
<div id="appSecond" style="height:100%">
<template>
<span>{{message}}</span>
</template>
</div>
</body>
</html>
When I open the second screen with the OpenNewPage method, I cannot access both the store object and the components I want to use do not work. I was try it;
second.js
const app2 = createApp({
});
export { app2 };
and my method
import { app2 } from "../second.js";
openNewPage(){
var t = window.open('second.html','newMonitor','height=700,width=700,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes');
if (t) {
t.onload = function () {
t.window.app = app2;
app2.mount("#appSecond");
}
}
}
Somehow I try to run in second.html but I get a warning like "[Vue warn]: Failed to mount app: mount target selector". The code didn't work anyway. Can you help me?
openNewPage() can't run a script for the newly opened page; only the new page could run its own scripts. When openNewPage() tries app2.mount(), it's running that code on its own page (not the new one), leading to the error you observed.
Solution
Remove the mounting code from openNewPage() so that it only opens the new page:
export default {
openNewPage() {
window.open('second.html', …);
}
}
Update second.html to load the script that mounts the app, and remove the unnecessary <template> within the <div id="appSecond">:
<body>
<div id="appSecond" style="height:100%">
<span>{{message}}</span>
</div>
<script src="./second.js"></script>
</body>
In second.js, add the code that mounts your app:
// second.js
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
createApp(App).use(store).mount('#appSecond')

Avoid Duplicate Meta Description and Keywords in Next.js

I'm developing my website with Next.js To upgrade my website's SEO performance, I'm trying to avoid duplicated meta tags.
My Question
In Next official docs, they say that I can avoid overlapped meta tag by insert key property in meta tag. But this does not work.
<meta name="description" content="~~" key="titleDescription"/>
<meta name="keywords" content="~~" key="titleKeywords"/>
These are default rootDocument meta tags and,
<meta name="description" content={item.product_description} key="titleDescription"></meta>
<meta name="keywords" content={item.brand_name} key="titleKeywords"></meta>
These are dynamically generated meta tags in item pages.
In deployed browser, there are still two description and keywords meta tags in website. I want to avoid duplicated meta tag. Thank you for your help!
There are a few things to watch for when using Next.js Head components.
The _document Head component is next/document
Tags in _document will not be replaced (can be duplicated) even with a key identifier
The _app Head component is next/head
Tags in _app can be in child components
Tags in _app can be overridden with the key identifier
Tags in pages cannot be in child components
Tags in pages can override tags with the same key identifier.
Examples
_document.{js|jsx|ts|tsx}
Scripts, styles, and other tags you need access to immediately - Next will likely not be fully mounted at this point. You cannot replace tags in the document/head component with the key attribute.
import Document, {Head, Html, Main, NextScript } from 'next/document';
class MyDocument extends Document {
render = () => (
<Html lang="en-US" dir="ltr">
<Head>
<script src="/some-script.js" defer={false} />
<style>.inline-styles{}</style>
{/* META & TITLE TAGS PLACED HERE CANNOT BE OVERRODE */}
</Head>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
OR self-closing Head tag
class MyDocument extends Document {
render = () => (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
Note: import is from next/document
_app.{js|jsx|ts|tsx}
import Head from 'next/head';
const App = ({ Component, pageProps }) => (
<>
<Head>
<title key="title">App Tittle</title>
</Head>
<Component {...pageProps} />
</>
);
OR load from a custom component
import Head from 'next/head';
const MyHeadTags = () => (
<Head>
<title key="title">App Tittle</title>
<meta key="description" name="description">Description</meta>
</Head>
);
const App = ({ Component, pageProps }) => (
<>
<MyHeadTags />
<Component {...pageProps} />
</>
);
Note: import is from next/head
some_page.{js|jsx|ts|tsx}
const SomePage = () => (
<>
<Head>
<title key="title">Some Page Tittle</title>
<meta key="description" name="description">Some Page Description</meta>
</Head>
<div>My Page</div>
</>
);
NOT ALLOWED
The head component must be on the page and cannot be a child component. If it's a child component, it sometimes will not override other tags with the same key property.
some_page.{js|jsx|ts|tsx}
const MyHeadTags = () => (
<Head>
<title key="title">Some Page</title>
<meta key="description" name="description">Some Page Description</meta>
</Head>
);
const ChildComponent = () => (
<>
<MyHeadTags />
Info.
</>
);
const SomePage= () => (
<>
<ChildComponent />
<div>Will not work</div>
</>
);
Update: The last example seems to work in some cases with Next 11+, but I have run into a few instances where it duplicates tags. I avoid the last method.
UPDATE
Here's what Next.js docs say regarding the <Head /> element within the _document.js file:
The component used here is not the same one from next/head.
The component used here should only be used for any
code that is common for all pages. For all other cases, such as
<title> tags, we recommend using next/head in your pages or
components.
Source: https://nextjs.org/docs/advanced-features/custom-document
Therefore, Next.js recommends that all the dynamic <meta /> tags should only be defined on an individual page level.
ORIGINAL ANSWEAR (it seemed to work at first, but as it turns out, only at random).
This issue seems to appear when you mix up two ways of closing empty HTML tags in JSX. Notice that your meta tags in the _document.js file are self-closing: <meta /> and the dynamic ones are not: <meta></meta>.
Ensure you are consistent with it (i.e. according to best practices you should convert all empty tags to the self-closing variant) and you should be fine.
I believe you can take a look at this package that helps managing meta tags https://github.com/garmeeh/next-seo in Next.js project. It helped me :D
For your question, yea try putting the Head in the _app instead of _document. _document is like non mutated one.. it will be always in the website. Cheers 🥂
I use Next 12.
Thanks to Sean's comment here, I was able to progress.
I personally update the tags for SEO purpose according to the consulted page with a component Seo that I crafted.
But to prevent importing it in every pages, I wanted to import it once. It happened that importing this Seo component in pages/_app.js was eventually just duplicating the tags and especially breaking my social media links.
So here is my code.
First the Seo component:
import Head from 'next/head'
import {SEO} from '#/Constants/seo'
const titlePrepend = 'WeekandGO | '
const Seo = ({ seo }) => {
const currentUrl = typeof window !== 'undefined' && window.location.href
const defaultSeo = {...SEO['index']}
let seoWithDefaults = {...defaultSeo}
if (seo) {
seoWithDefaults = {
...seoWithDefaults,
...seo,
}
}
const fullSeo = {
...seoWithDefaults,
metaTitle: seoWithDefaults?.metaTitle ? `${titlePrepend}${seoWithDefaults.metaTitle}` : `${titlePrepend}${defaultSeo.metaTitle}`,
shareImage: seoWithDefaults?.shareImage || defaultSeo.shareImage,
metaDescription: seoWithDefaults?.metaDescription || defaultSeo.metaDescription,
}
return <Head>
<title>{fullSeo.metaTitle}</title>
<meta name="Author" lang="fr" content="Leb Communication"/>
<meta name="Identifier-URL" content="www.weekandgo.com"/>
<meta name="Reply-to" content=""/>
<meta name="revisit-after" content="7"/>
<meta name="Publisher" content="WeekandGO"/>
<meta name="Copyright" content="WeekandGO"/>
<link rel="canonical" href="https://www.weekandgo.com/" />
<meta name="keywords" content={fullSeo.metaKeywords} />
<meta name="description" content={fullSeo.metaDescription} />
<meta name="image" content={fullSeo.shareImage} />
<meta property="og:site_name" content="WeekandGO" />
<meta property="og:url" content={currentUrl || 'https://www.weekandgo.com/'} />
<meta property="og:type" content="website" />
<meta property="og:image" content={fullSeo.shareImage} />
<meta property="og:title" content={fullSeo.metaTitle} />
<meta property="og:description" content={fullSeo.metaDescription} />
<meta name="twitter:title" content={fullSeo.metaTitle} />
<meta name="twitter:description" content={fullSeo.metaDescription} />
<meta name="twitter:image" content={fullSeo.shareImage} />
</Head>
}
export default Seo
I use it in pages/_document.js:
class MyDocument extends Document {
render() {
return (
<Html lang="fr">
<Head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
<meta name="theme-color" content="#000000" />
<link rel="apple-touch-icon" href="/logo192.png" />
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap&subset=latin-ext" rel="stylesheet" />
<link rel="stylesheet" href="https://use.typekit.net/uah4cdm.css" />
<link rel="manifest" href="/manifest.json" />
<script src="https://maps.googleapis.com/maps/api/js?key=<key>" type="text/javascript"/>
</Head>
<Seo/>
<body className={ !isMobile && 'u-hover-on'}>
<Main />
<NextScript />
</body>
</Html>
)
}
}
Then I import this component in pages/_document.js as so:
import Document, { Html, Head, Main, NextScript } from 'next/document'
import { isMobile } from 'react-device-detect'
import Seo from '#/Shared/Seo'
class MyDocument extends Document {
render() {
return (
<Html lang="fr">
<Head>
<link rel="icon" href="/favicon.ico" />
<meta name="theme-color" content="#000000" />
<link rel="apple-touch-icon" href="/logo192.png" />
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap&subset=latin-ext" rel="stylesheet" />
<link rel="stylesheet" href="https://use.typekit.net/uah4cdm.css" />
<link rel="manifest" href="/manifest.json" />
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDiB40c-5x-GAEBw3mIJXPTvamFHUV536I" type="text/javascript"/>
</Head>
<Seo/>
<body className={ !isMobile && 'u-hover-on'}>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
Then, let me spare you some lines to just look at the return of my functional component App in pages/_app.js. There is no import of Seo component, only a ** Head coming from 'next/head' ** is used :
...
return (<SessionProvider session={session}>
<TokensRefresher/>
<Head>
<meta charSet="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</Head>
<GlobalContextProvider appProps={{ global, categoryAnnexes, categoriesInfos }}>
<GlobalLayout error={error}>
<Component {...rest} />
</GlobalLayout>
</GlobalContextProvider>
</SessionProvider>)
}
...
And finally, here is a page I receive data from server side props and that I want to use to change the meta tags related to seo. Here again I don't show the part of the code that are useless for the matter :
...
const Annonce = ({ ad, ...pageProps }) => {
return <>
<Seo seo={{metaTitle: ad?.slug, metaDescription: ad?.dealerWord, shareImage: ad?.firstImage?.fileUrl}} />
<AnnonceLayout ad={ad} {...pageProps} />
</>
}
...
The result I have in the source code is there is no duplicated meta tags and I can share my links on social medias with no image, description or page tilte overlaps

why is my index.html file returning a blank screen whenever i debug or preview it?

this is the app.js file
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import DashboardLayout from './layouts/DashboardLayout';
import './faithdash/scss/styles.scss';
export default function App() {
return (
<BrowserRouter>
<Switch>
<Route component={DashboardLayout} />
</Switch>
</BrowserRouter>
);
}
this is the index.html file
ive tried everything and have used different my vscode index chrome previewer to view the index file like others but its shows a blank screen
<!DOCTYPE html>
<html lang="en">
<head>
<title> Faithpays dashboard</title>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.png" />
<link
href="https://%PUBLIC_URL%/evergreen.eot"
rel="font"
/>
<link
href="https://%PUBLIC_URL%/evergreen.css"
rel="stylesheet"
crossorigin="anonymous" />
</head>
<body>
<div id="app"></div>
<script src="app.js"></script>
<script src="_nav.js"></script>
</body>
</html>
Because you didn't call render function from ReactDOM.
See more here: https://reactjs.org/docs/getting-started.html

Can't close a JSX. Parsing error: Unterminated JSX contents

I just want to try out a Hello World of an UI framework for React, called CoreUI.
But it says I got my JSX wrong and unclosed. But I already closed all } and ), so please tell me what am I doing wrong here?
Thanks
import React from 'react';
import ReactDOM from 'react-dom';
const App = () => {
return (
<html lang="en">
<head>
// Required meta tags
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
// CoreUI CSS
<link rel="stylesheet" href="https://unpkg.com/#coreui/coreui#3.0.0-rc.0/dist/css/coreui.min.css" crossorigin="anonymous" />
<title>CoreUI<title/>
<head/>
<body class="c-app">
<h1>Hello, world!<h1/>
// Optional JavaScript
// Popper.js first, then CoreUI JS
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.15.0/umd/popper.min.js" integrity="sha384-L2pyEeut/H3mtgCBaUNw7KWzp5n9+4pDQiExs933/5QfaTh8YStYFFkOzSoXjlTb" crossorigin="anonymous"><script/>
<script src="https://unpkg.com/#coreui/coreui#3.0.0-rc.0/dist/js/coreui.min.js"><script/>
<body/>
<html/>
);
};
ReactDOM.render(
<App />, document.querySelector('#root')
);
Meta tags are not closed. Try this:
import React from 'react';
import ReactDOM from 'react-dom';
const App = () => {
return (
<html lang="en">
<head>
// Required meta tags
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
// CoreUI CSS
<link rel="stylesheet" href="https://unpkg.com/#coreui/coreui#3.0.0-rc.0/dist/css/coreui.min.css" crossorigin="anonymous" />
<title>CoreUI<title/>
<head/>
<body class="c-app">
<h1>Hello, world!<h1/>
// Optional JavaScript
// Popper.js first, then CoreUI JS
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.15.0/umd/popper.min.js" integrity="sha384-L2pyEeut/H3mtgCBaUNw7KWzp5n9+4pDQiExs933/5QfaTh8YStYFFkOzSoXjlTb" crossorigin="anonymous"><script/>
<script src="https://unpkg.com/#coreui/coreui#3.0.0-rc.0/dist/js/coreui.min.js"><script/>
<body/>
<html/>
);
};
ReactDOM.render(
<App />, document.querySelector('#root')
);
Your closing tags are not proper.it should be
import React from 'react';
import ReactDOM from 'react-dom';
const App = () => {
return (<html lang="en">
<head>
// Required meta tags
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
// CoreUI CSS
<link rel="stylesheet" href="https://unpkg.com/#coreui/coreui#3.0.0-rc.0/dist/css/coreui.min.css" crossorigin="anonymous" />
<title>CoreUI</title>
</head>
<body class="c-app">
<h1>Hello, world!</h1>
// Optional JavaScript
// Popper.js first, then CoreUI JS
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.15.0/umd/popper.min.js" integrity="sha384-L2pyEeut/H3mtgCBaUNw7KWzp5n9+4pDQiExs933/5QfaTh8YStYFFkOzSoXjlTb" crossorigin="anonymous"></script>
<script src="https://unpkg.com/#coreui/coreui#3.0.0-rc.0/dist/js/coreui.min.js"></script>
</body>
</html>
);
};
ReactDOM.render(
<App />, document.querySelector('#root')
);

Categories