I want to pass an image as a prop to another page - javascript

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>
)
}

Related

How to send input from one React component to other?

I want to create a login page. When the user submits the form, the username should be rendered on the dashboard. I am unable to figure that out.
import React from "react";
import Footer from "./Footer";
import Back from "./Back";
import { Link } from "react-router-dom";
const Login = () => {
return (
<div>
<Back />
<div>
<form className="login-form">
<h1 className="form-heading">Login</h1>
<input
className="form-input"
type="text"
placeholder="Enter your Username"
/>
<input
className="form-input"
type="password"
placeholder="Enter your password"
/>
<button className="form-button">
<Link to={"/dashboard"}>Login</Link>
</button>
</form>
</div>
<Footer />
</div>
);
};
export default Login;
To share data between two components, the standard react approach is to lift the state up to a parent component, then pass it down (through props or context). For example:
const App = () => {
const [user, setUser] = useState();
return (
<Routes>
<Route path="/login" element={<Login setUser={setUser}/>}
<Route path="/dashboard" element={<Dashboard user={user}/>}
</Routes>
)
}
const Login = ({ setUser }) => {
return (
// ...
<Link to="/dashboard" onClick={() => setUser('bob')}
// ...
);
}
const Dashboard = ({ user }) => {
return (
<div>
Hello {user}!
</div>
)
}

Params not working with react and netlify

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>
);
}

How to pass an array object from a component to a page in reactjs

Child
import React from "react";
import { Link } from "react-router-dom";
import "../pages/All.css";
const MovieList = (props) => {
return(
<>
{props.movies.map((movie, index) => (
<div className="ro">
<img src={movie.Poster} alt={movie.Title} /> <br /> <br />
<label>{movie.Title}</label> <br />
<p>{movie.Type} {movie.Year}</p> <br /> <br />
<div className="overlay">
<li><Link to = "/play" class="popup-video btn">Watch</Link></li>
<li><Link to ="movie-details.html" class="btn">Download</Link></li>
</div>
</div>
))}
</>
);
};
export default MovieList;
import React from "react";
import ReactPlayer from "react-player";
function Play(movie){
return(
<div>
<ReactPlayer width="100%" height="750px" controls url ={"http://www.youtube.com/"+movie.Title} />
</div>
);
}
export default Play;
i am trying to pass {movie.Title} to controls url in Parent Component
I hope what you want to ask is how to pass params.
const MainNavigation = ()=> (
<Routes>
<Route path="/" element={<VideoList />} />
<Route path="/play:id" element={<Play />} />
</Routes>
)
const VideoList = ()=> (
<Link to={"/play/" + movie.title}>{movie.title}</Link>
)
const Play = ()=> {
const {id} = useParams();
return (
<VideoComponent url={"https://example.com/" + id} />
)
}
For more information, read official documents. https://reactrouter.com/docs/en/v6/hooks/use-params

Why is my ProtectedRoutes component broken?

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;

React-router-dom v6, URL changing but component doesn't render

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.

Categories