Onclick redirect with PARAMS in react is not working in Netlify
Hi everyone, I'm struck in a problem which works fine with localhost but creates issue with netlify.
I want to pass data onclick to a react js page via params, this works file on local host but give 404 when I tried to host this app on netlify.
Please Visit my site
As you can see on second page when I click on play video, it gives me 404.
For your clarity I'll provide my code to you.
App.js
function App() {
const style1 = {
display: "flex",
minHeight: "100vh",
flexDirection: "column",
};
return (
<div className="App">
<div style={style1}>
<HeaderComp />
<Routes>
<Route exact path="/" element={<FirstPage />} />
<Route exact path="/SecondPage" element={<SecondPage />} />
<Route
path="/ThirdPage/:url/:one/:two/:three/:four"
element={<ThirdPage />}
/>
<Route exact path="/About" element={<About />} />
<Route path="*" element={<FirstPage />} />
</Routes>
</div>
<FooterComp />
</div>
);
}
export default App;
Params giving Component
import React from "react";
// import { Link } from "react-router-dom";
export default function VideoCard({ data }) {
const style1 = {
width: "18rem",
};
return (
<div className="m-3 ">
<div className="card" style={style1}>
<img src={data.imageUrl} className="card-img-top" alt="..." />
<div className="card-body">
<h5 className="card-title">{data.videoTitle}</h5>
<p className="card-text">{data.videoDescription}</p>
<a
href={"/ThirdPage/" + data.videoUrl.substr(26)}
className="btn btn-primary"
>
Play Video
</a>
</div>
</div>
</div>
);
}
Params Recieving Component
import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
export default function ThirdPage() {
const params = useParams();
const [url, updateUrl] = useState("");
useEffect(() => {
const url1 =
"http://res.cloudinary.com" +
`/${params.url}/${params.one}/${params.two}/${params.three}/${params.four}`;
updateUrl(url1);
}, [url, params]);
return (
<div className="container mb-5">
{url && (
<div className="row">
<h1>This is Third page</h1>
<video width="750" height="500" controls loop autoPlay>
<source src={url} type="video/mp4" />
</video>
</div>
)}
</div>
);
}
Related
I have a personal project I'm working on and I have run into a bit of a problem. I have two simple code snippets one for the component and one for handling the route.
import { Routes, Route } from "react-router-dom";
function setPath {
return (
<Routes>
<Route path="/sect/guest" element={<MobileCardsGuest />} />
<Routes/>
)
} ```
the setPath component is called in App.js
component to be displayed
import React from "react";
import eventIcon from "../../assets/img/red-carpet.png";
import mealIcon from "../../assets/img/hamburger.png";
import accIcon from "../../assets/img/accomodation.png";
import "../../assets/css/mobilecards.css";
import { Link } from "react-router-dom";
import { toast } from "react-toastify";
function MobileCardsGuest() {
const notify = ()=>{
return toast.info("Coming Soon")
}
return (
<div className="mobile-card">
<p className="text-center mob-title">
<b style={{ color: "var(--pieme-color)" }}>You are Welcome</b>
</p>
<p className="text-center mob-body">Please choose what you would like</p>
<div class="card bg-light m-card">
<p></p>
<img src={mealIcon} className="iconimg" alt="Meal Icon"/>
<div class="card-body text-center">
<p class="card-text">Meal</p>
</div>
</div>
<div class="card bg-light m-card">
<p></p>
<img src={accIcon} className="iconimg" alt="Acc Icon" />
<div class="card-body text-center">
<p class="card-text">Accomodation</p>
</div>
</Link>
</div>
<div class="card bg-light m-card" onClick={notify}>
<p></p>
<img src={eventIcon} className="iconimg" alt="Event Icon"/>
<div class="card-body text-center">
<p class="card-text">Event</p>
</div>
</div>
</div>
);
}
export default MobileCardsGuest;
the other component
import useNavigate from "react-router-dom"
const navigate= useNavigate();
function Navbar{
return (
<button onClick={() => {navigate("/sect/guest")>
Guest
</button>
)
}
When I run the above and go to the path"/sect/guest"` it doesn't display the component.
If you are using react 18 or latest react-router-dom then your routes structure would be like :
<Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/cart" element={<Cart />} />
</Routes>
<Router>
Here BrowserRouter and switch will not beused in newer version applications.
You need to import BrowserRouter as well.
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import MobileCardsGuest from './path/MobileCardsGuest';
const SetPath = () => {
return (
<BrowserRouter>
<Routes>
<Route exact path='/sect/guest' element={<MobileCardsGuest />} />
</Routes>
... ...
</BrowserRouter>
);
}
export default SetPath;
I just tried to follow this question with no results for me.
The point is that I'm trying to get a selected pokemon from a component and pass down to another component. The data is correctly passed, some data are displayed, but with other (for example, the sprites) I got an error. I'm using Context by the way.
PokemonContext.js
import React, { useState } from 'react';
const Context = React.createContext({});
export function PokemonsContextProvider({ children }) {
const [favorites, setFavorites] = useState([]);
return <Context.Provider value={{ favorites, setFavorites }}>{children}</Context.Provider>;
}
export default Context;
App.js
<PokemonsContextProvider>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/pokemons" element={<PokemonsList />} />
<Route path="/favorites" element={<Favorite />} />
<Route path="/pokemon/:name" element={<PokemonDetails />} />
<Route path="*" element={<NotFound />} />
</Routes>
</PokemonsContextProvider>
PokemonsDetails.js
const PokemonDetails = () => {
const { name } = useParams();
const [pokemon, setPokemon] = useState('');
useEffect(() => {
pokemonService.pokemonDetail(name).then((res) => {
setPokemon(res);
});
}, []);
return (
<div>
<h1 className="text-center mb-4">Details for {name.toUpperCase()}</h1>
<PokemonCard pokemon={pokemon} />
<div className="text-center">
<Link className="btn btn-success mx-2 my-4" to="/favorites">
Go back
</Link>
</div>
</div>
);
};
PokemonCard.js
const PokemonCard = ({ pokemon }) => {
return (
<div className="card text-center bg-primary">
<div className="card-body">
<h5 className="card-title">{pokemon.name}</h5>
</div>
<ul className="list-group list-group-flush">
<li className="list-group-item">Weight: {pokemon.weight}</li>
<li className="list-group-item">Height: {pokemon.height}</li>
</ul>
</div>
);
};
export default PokemonCard;
When I add this line <img className="card-img-top" src={pokemon.sprites.front_default} alt="Card image cap" /> to the PokemonCard component I got this error:
The data is correctly displayed when I console log it, so, I don't know why I'm having this error. If I inspect the React Dev Tools the data is in the component!
The PokemonCard.js component is being rendered before the result of the request.
You can resolve this problem checking if there is a pokemon before use his props.
const PokemonCard = ({ pokemon }) => {
return pokemon && (
<div className="card text-center bg-primary">
<img className="card-img-top" src={pokemon.sprites?.front_default} alt="Card image cap" />
<div className="card-body">
<h5 className="card-title">{pokemon.name}</h5>
</div>
<ul className="list-group list-group-flush">
<li className="list-group-item">Weight: {pokemon.weight}</li>
<li className="list-group-item">Height: {pokemon.height}</li>
</ul>
</div>
);
};
export default PokemonCard;
I am reusing this component from another project, and I can't figure out why it doesn't work in this one despite working in the other one.
It should check if the user has a token in their cookies, and then redirect to the homepage if they don't. If they do, they should see the component.
I'm not receiving any errors. The page always redirects to the homepage.
ProtectedRoutes.js
import React from "react";
import { Navigate } from "react-router-dom";
import Cookies from "universal-cookie";
const cookies = new Cookies();
export default function ProtectedRoutes({component: Component, ...rest}) {
//get the cookie if there is one
const token = cookies.get("TOKEN");
//if there is a valid cookie, show component, otherwise go to homepage
return token ? <Component /> : <Navigate to="/" />
}
App.js
import './App.css';
import React from 'react';
import {BrowserRouter, Routes, Route, Link} from 'react-router-dom';
import HomeScreen from './Components/HomeScreen';
import LoginScreen from './Components/LoginScreen';
import RegisterScreen from './Components/RegisterScreen';
import AccountScreen from './Components/AccountScreen';
import PreferencesScreen from './Components/PreferencesScreen';
import ProtectedRoutes from './Components/ProtectedRoutes';
import Cookies from 'universal-cookie';
const cookies = new Cookies();
function App() {
const openMenu = () => {
document.querySelector(".sidebar").classList.add("open");
}
const closeMenu = () => {
document.querySelector(".sidebar").classList.remove("open");
}
const logout = (e) => {
e.preventDefault();
cookies.remove("TOKEN", {path: "/"});
window.location.href="/"
}
return (
<BrowserRouter>
<div className="container">
<header className="header">
<div className="brand">
<button className="sidebar-button" onClick={openMenu}>
☰
</button>
<Link to="/" >Title</Link>
</div>
<div className="header-links">
<Link to="/signin" >Sign In</Link>
<Link to="/myaccount/" >My Account</Link>
<Link to="/logout" onClick={(e) => logout()}>Logout</Link>
</div>
</header>
<aside className="sidebar">
<button className="sidebar-close-button" onClick={closeMenu}>x</button>
<div className="sidebar-links">
<h4>New Entry</h4>
<h4>New Entry</h4>
</div>
</aside>
<main className="main">
<div className="content">
<Routes>
<Route exact path="/" element={<HomeScreen />} />
<Route exact path="/register" element={<RegisterScreen />} />
<Route exact path="/signin" element={<LoginScreen />} />
<Route exact path="/myaccount" element={<ProtectedRoutes component={AccountScreen} />} />
<Route exact path="/preferences" element={<PreferencesScreen />} />
</Routes>
</div>
</main>
</div>
</BrowserRouter>
);
}
export default App;
The main problem is that this image is selected from the file explorer and I am using react-router.
Add.js
this is where you select the image
import { Link } from "react-router-dom";
import About from "./About";
import './styles/modal.css'
import firebase from "firebase";
require("firebase/firestore")
require("firebase/storage")
export default function Add(props) {
const [image, setImage] = useState(null);
const [modal, setModal] = useState(false);
const pickImage = (event) => {
//console.log();
setImage(URL.createObjectURL(event.target.files[0]));
//console.log(image);
}
const toggle = () => {
setModal(!modal);
}
return (
<div>
<h1>Add</h1>
<button onClick={toggle}>Add image</button>
{modal ? (
<div className="modal-bg">
<div className="modal">
<img src={image} style={{ width: '60%', height: '60%' }} className="ex-img" />
<br /><br />
<label htmlFor="fie" className="gcoo btn-default">+ File
<input id="fie" type="file" onChange={pickImage} className="file-pick" />
</label>
<br />
<br />
<div className="bottom-buttons">
<Link to="/about">
<button className="save">Save</button>
</Link>
<button onClick={() => setModal(false)} className="closse">Close</button>
</div>
</div>
</div>
) : null}
</div>
)
}
I am using firebase but not in this file so you can ignore this.
MainRoutes.js
this is where all the routes and pages are.
import { Route } from "react-router";
import { Switch } from 'react-router-dom';
import ImageDisplay from "./components/ImageDisplay";
import Add from './components/Add';
export default function MainRoute(props) {
return (
<Switch>
<Route exact path="/about" component={() => <ImageDisplay />} />
<Route exact path="/add" component={() => <Add />} />
</Switch>
);
}
finally this file ImageDisplay.js is where the image should be displayed
I dont have much on this file because i dont know how to put in any images.
I have tried props but whenever i imported the Imagedisplay it always showed the content on it and i dont want anything from image display. I only want to send an image over there.
import React from 'react'
import { Link } from "react-router-dom"
function ImageDisplay(props) {
return (
<div>
<h1>image</h1>
<div>
<img />
<p></p>
</div>
</div>
)
}
export default ImageDisplay;
Make sure that you are not reloading the page when moving between the two routes, since this will remove all state.
To share state between the two components you would need to store the state in the parent, and pass it to the children.
Add:
export default function Add(props) {
const pickImage = (event) => {
props.setImage(URL.createObjectURL(event.target.files[0]));
}
// The rest of your function
}
And in your parent:
export default function MainRoute(props) {
const [image, setImage] = useState(null)
return (
<Switch>
<Route exact path="/about" component={() => <ImageDisplay image={image} />} />
<Route exact path="/add" component={() => <Add setImage={setImage} />} />
</Switch>
);
}
You can now access the image prop in your imageDisplay.
function ImageDisplay(props) {
return (
<div>
<h1>image</h1>
<div>
<img src={props.image} />
<p></p>
</div>
</div>
)
}
I've tried everything but fail to render component when URL changes. No error messages nothing, it renders Home component but when i click on (view and edit icon)Link it just changes url, component does not render nothing happens. I couldn't find a solution, is there any way to make it work?
App.js
import "./App.css";
// import { TextFilledComp } from './Components/TextFilledComp';
import { Routes, Route } from "react-router-dom";
import { SingleTodoPage } from "./Components/SingleTodoPage";
import { EditTodo } from "./Components/EditTodo";
import { Home } from "./Components/Home";
function App() {
return (
<div>
<Routes>
<div>
<div className="header-text">Todo List</div>
<div className="box">
<Route exact path="/" element={<Home />} />
<Route path="/todo/:todoId" element={<SingleTodoPage />} />
<Route path="/edit/:TodoId" element={<EditTodo />} />
</div>
</div>
</Routes>
</div>
);
}
export default App;
Todo.js
import {
Checkbox,
List,
ListItem,
ListItemSecondaryAction,
ListItemText,
makeStyles
} from "#material-ui/core";
import DeleteIcon from "#material-ui/icons/Delete";
import EditIcon from "#material-ui/icons/Edit";
import CheckBoxIcon from "#material-ui/icons/CheckBox";
import React from "react";
import { useSelector } from "react-redux";
import { Link } from "react-router-dom";
const useStyles = makeStyles({
listRoot: {
borderWidth: "1px",
borderColor: "#aaaaaa",
borderStyle: "solid",
borderRadius: "20px"
}
});
export const TodoList = () => {
const todos = useSelector((state) => state.todo);
const classes = useStyles();
return (
<div style={{ width: "95%", margin: "10px auto" }}>
<List>
{todos.map((todo) => (
<ListItem key={todo.id} className={classes.listRoot}>
<ListItemText primary={todo.name} />
<ListItemSecondaryAction>
{/* <Checkbox
edge="end"
/> */}
<CheckBoxIcon color="primary" />
<DeleteIcon color="secondary" />
<Link to={`/edit/${todo.id}`} className="button">
<EditIcon />
</Link>
<Link to={`/todo/${todo.id}`}>view</Link>
</ListItemSecondaryAction>
</ListItem>
))}
</List>
</div>
);
};
codesandbox link for complete app
A Routes component is the replacement for Switch from v5 and should only wrap around Route components. It's solely responsible for matching the provided paths and controlling the visibility of Routes and does not know what to do with regular JSX.
function App() {
return (
<div>
<div>
<div className="header-text">Todo List</div>
<div className="box">
<Routes>
<Route path="/" element={<Home />} />
<Route path="/todo/:todoId" element={<SingleTodoPage />} />
<Route path="/edit/:todoId" element={<EditTodo />} />
</Routes>
</div>
</div>
</div>
);
}
I've also removed the exact prop as it is deprecated in v6 since all Routes are exact by default. To allow non-exact Routes, use the new path="/nonexact/*" syntax. Some more info on the new features can be found here.