I am trying to open a PDF in new tab in React JS. The code is attached below. The issue I am having is that my pdf file is having its name altered in the new tab. The tab header becomes sampe.e72672.pdf. I do I just make it sample? Also how do I define a hard coded URL for the new tab?
import React from "react";
import Resume from "../static/sample.pdf";
return (
<div className="MainLandingContainer">
<div className="ResumeContainer">
<Button variant="primary" target="_blank" href={Resume}>
Resume
</Button>
</div>
</div>
);
}
export default Landing;
I think we can't change the baseURL of a window without reloading to a new URL. But we can change the path using history.pushState. Here is a solution which is working in Mozilla and Chrome.
import React from "react";
import Resume from "./Sample.pdf";
const Landing = () => {
const openPDF = () => {
const pdfWindow = window.open("test");
const title = "My PDF";
const URI = "test/test";
const html = `
<html>
<head>
<title>${title}</title>
</head>
<body style="margin:0">
<embed width="100%" height="100%" src=${Resume} type="application/pdf">
</body>
</html>
`;
pdfWindow.document.write(html);
pdfWindow.document.close();
pdfWindow.history.pushState(null, null, URI);
};
return (
<div className="MainLandingContainer">
<div className="ResumeContainer">
<button variant="primary" target="_blank" onClick={openPDF}>
Resume
</button>
</div>
</div>
);
};
export default Landing;
You can find the codesandbox here
Related
New to Google AMP pages. Basically, I am trying to access the AMP State to determine whether or not a div should remain hidden:
import React from 'react';
const MyButton = (props) => {
return (
<>
<Head>
<script async src="https://cdn.ampproject.org/v0.js"></script>
</Head>
<div>
<amp-state id="showHiddenContent" show="false"></amp-state>
<button
type="button"
on="tap:AMP.setState({showHiddenContent: { show: !showHiddenContent.show}})"
>
Show More
</button>
<div hidden={!AMP.getState('showHiddenContent').show}>
<p>Show this when the showHiddenContent state evaluates to true</p>
</div>
</div>
</>
);
};
export default MyButton;
I am met with the following error located on the div tag:
'AMP' is not defined
Any thoughts how I can correct this? I've added the script tag in the HEAD of the component but still get the same error. Thanks!
I am doing a React App and trying to make a image slider.
I am working in replit.com and in the React App the JS won't work. When I made it in a simple Repl (HTML, CSS and Vanilla.js only) works perfectly.
When I try to do a query select and console log the ul with the className="carousel-track" prop out I get null so it breaks it all.
Carousel component:
import React from 'react';
import Slide from "./Slide";
import Dot from "./Dot"
import "../css/carousel.scss";
// import "../js/carousel.js"
export default function Carousel(props) {
const { players } = props;
const allSlides = players.map(player => {
return <Slide
key={player.key}
name={player.name}
team={player.team}
img={player.img}
/>
});
const allDots = players.map(player => {
return <Dot key={players.indexOf(player)}/>
})
return (
<div className="carousel">
<button className="carousel-btn btn-left">
<i className="fa-solid fa-paper-plane"></i>
</button>
<div className="carousel-track-container">
<ul className="carousel-track">
{allSlides}
</ul>
</div>
<button className="carousel-btn btn-right">
<i className="fa-solid fa-paper-plane"></i>
</button>
<div className="carousel-nav">
{allDots}
</div>
</div>
)
}
And the logic is exactly the same with the one that you can see in the Sources Inspect tab at this link.
If I uncomment that import "../js/carousel" it breaks and nothing is rendered in the page
While developing a website for a class (I used a youtube tutorial to build the site), I am having this error show up in the console:
Although the site renders locally, this causes issues when I try to deploy it, as you can imagine. So I found the documentation for the React.forwardRef() and I implemented it like this in my code:
import React from 'react';
import Image from "next/image";
import styles from "../styles/PizzaCard.module.css";
import Link from 'next/link';
const PizzaCard = React.forwardRef(({pizza}, ref) => {
return <input ref={ref}/>>(
<div className={styles.container}>
<Link href={`/product/${pizza._id}`} passHref>
<Image src={pizza.img} alt="" width="500" height="500"/>
</Link>
<h1 className={styles.title}>{pizza.title}</h1>
<span className={styles.price}>${pizza.prices[0]}</span>
<p className={styles.desc}>
{pizza.desc}
</p>
</div>
);
});
export default PizzaCard;
And this in my PizzaList file:
import React from "react";
import styles from "../styles/PizzaList.module.css";
import PizzaCard from "./PizzaCard";
const PizzaList = React.forwardRef(({pizzaList}, ref) => {
return <input ref={ref}/>> (
<div className = {styles.container}>
<h1 className={styles.title}>The Mellowist Pizza in Town!</h1>
<p className={styles.desc}>
Mellow Yellow Pizzaria is a local Family Owned business providing
the community with tasty pizza made with Heart and Soul!
</p>
<div className={styles.wrapper}>
{pizzaList.map((pizza) => (
<PizzaCard key={pizza._id} pizza={pizza} />
))}
</div>
</div>
)
})
export default PizzaList
And here is where PizzaList is called:
import axios from "axios";
import Head from "next/head";
import Image from "next/image";
import { useState } from "react";
import Add from "../components/Add";
import AddButton from "../components/AddButton";
import Featured from "../components/Featured";
import PizzaList from "../components/PizzaList";
import styles from "../styles/Home.module.css";
export default function Home({pizzaList, admin}) {
const [close, setClose] = useState(true)
return (
<div className={styles.container}>
<Head>
<title>Mellow Yellow Pizzaria</title>
<meta name="description" content="Created by Yellow project team at CTU" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Featured/>
{admin && <AddButton setClose={setClose}/>}
<PizzaList pizzaList={pizzaList} />
{!close && <Add setClose={setClose}/>}
</div>
)
}
export const getServerSideProps = async (ctx) =>{
const myCookie = ctx.req?.cookies || ""
let admin = false
if(myCookie.token === process.env.TOKEN){
admin = true
}
const res = await axios.get("http://localhost:3000/api/products")
return{
props:{
pizzaList:res.data,
admin,
}
}
}
Although this made the console errors go away, now my pizza products do not display, as you can see:
So, what am I doing wrong? If you need me to post more of my code, please let me know and I will, I'm not sure what all you'd need to see.
EDIT:
Here is my original code before adding the forwardRef()...this is the code that gives me the console errors in the first screenshot, I added the forwardRef() to PizzaCard and PizzaList because those are 2 spots that the console suggested I check (the list of "at ..." in the console window)
PizzaCard:
import React from 'react';
import Image from "next/image";
import styles from "../styles/PizzaCard.module.css";
import Link from 'next/link';
const PizzaCard = ({pizza}) => {
return (
<div className={styles.container}>
<Link href={`/product/${pizza._id}`} passHref>
<Image src={pizza.img} alt="" width="500" height="500"/>
</Link>
<h1 className={styles.title}>{pizza.title}</h1>
<span className={styles.price}>${pizza.prices[0]}</span>
<p className={styles.desc}>
{pizza.desc}
</p>
</div>
);
};
export default PizzaCard;
PizzaList:
import styles from "../styles/PizzaList.module.css";
import PizzaCard from "./PizzaCard";
const PizzaList = ({pizzaList}) => {
return (
<div className = {styles.container}>
<h1 className={styles.title}>The Mellowist Pizza in Town!</h1>
<p className={styles.desc}>
Mellow Yellow Pizzaria is a local Family Owned business providing
the community with tasty pizza made with Heart and Soul!
</p>
<div className={styles.wrapper}>
{pizzaList.map((pizza) => (
<PizzaCard key={pizza._id} pizza={pizza} />
))}
</div>
</div>
)
}
export default PizzaList
Here is a link to my github with all of the code:
https://github.com/InvisibleH3R0/mellowyellowpizzaria
Original Issue Fixed
So the fix for the ref issue was to wrap the image (in the first set of code I posted) in <a></a>
But now...when I load the site (locally) the homepage starts off just white, if I refresh the page it comes up...but when I inspect the page when first loading, it shows a internal server (500) error:
This leads me to believe the issue lies in the api/products or api/options code, that is where the GET methods are
I have these div cards with some information, and I would like to insert a link inside them, that redirects to another site. It didn't work with <a></a>. can anybody help me?
Thanks!
import React from "react";
function Card(props) {
return (
<div className="card">
<img className="img-logo" src={props.img} alt="image_logo" />
<h3 className="name"> {props.name}</h3>
<p className="paragraph"> {props.description}</p>
<a href={props.link}>Page</a>
</div>
);
}
export default Card;
You can use the <Link> component from react router.
If you are opening the url in new tab, make sure to use noopener and noreferrer so that the browser does not attach the current website's window variable to the newly opened url in the new tab, which can be a security loophole.
import { Link } from 'react-router-dom';
export const openInNewTab = (url) => {
const newWindow = window.open(url, '_blank', 'noopener,noreferrer');
if (newWindow) newWindow.opener = null;
};
function Card(props) {
return (
<div className="card">
<img className="img-logo" src={props.img} alt="image_logo" />
<h3 className="name"> {props.name}</h3>
<p className="paragraph"> {props.description}</p>
<Link href="#" onClick = {() => openInNewTab(props.link)}>Page</Link>
</div>
);
}
I want to create a basic web application using react. I have implemented creating buttons. I want to redirect to another page on button click. Below is my App.js code
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<p>
<buttontoolbar>
<button const path = '/Components'> Click Me </button>
</buttontoolbar>
</p>
</header>
</div>
);
}
export default App;
When i click on 'click me' button it should redirect to Components.js. Below is the code for Components.js
import React from "react"
function app(){
return(
<p>
Welcome to the world.
</p>
)
}
export default app
Long back i have done these king of things in ASP.NET. there i have used Response.redirect to redirect pages which is so simple. As I am new to React, i know nothing about this. Is there anything like that in React?
Basically React does not have "pages". The idea is more to "show" or "hide" components, this gives the user a page/view impression.
The easiest way to achieve routing in React is to use a declarative router library like react router especially for more complex apps.
Here is an example without react router to understand the basic concept:
const ViewOne = ({onClick}) => (
<div>
View 1 <br />
<button onClick={() => onClick("view2")}>Go to view 2</button>
</div>
);
const ViewTwo = ({onClick}) => (
<div>
View 2 <br />
<button onClick={() => onClick("view1")}>Go to view 1</button>
</div>
);
const App = () => {
const [currentView, setCurrentView] = React.useState("view1");
return (
<div>
{
currentView === "view1" ?
<ViewOne onClick={page => setCurrentView(page)} /> :
<ViewTwo onClick={page => setCurrentView(page)} />
}
</div>
);
};
const domContainer = document.querySelector('#my-app');
ReactDOM.render(<App />, domContainer);
<div id="my-app"></div>
<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>
Use react-router-dom package to define routing and then use one of below mentioned ways on onClick event of button.
this.props.history.push("componentpath").
browserHistory object (in react-router package).
Please refer this Link
try Link component of react-router-dom and pass to as a path to it wherever you want to redirect on onClick.
import { Link } from 'react-router-dom'
and Eg.
<Link to={'/Components'}>
<button > Click Me </button>
</Link>
const {Link, BrowserRouter} = window.ReactRouterDOM
function App(){
return (
<BrowserRouter>
<button><Link to='/abc' target='_blank'> Click Me </Link></button>
</BrowserRouter>
)
}
ReactDOM.render(<App/>, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/react-router-dom/umd/react-router-dom.min.js"></script>
<body><div id="root"></div></body>