Make div link to an React Element and pass props - javascript

I want to make it so when you click on a div it redirects you to another page, like react router but I have no knowledge to make it yet. Here is my code:
const Card: React.FC = ({ info }: any) => {
return (
<div className='card stacked featured'>
<img src={info.links.mission_patch} className='card_image' alt='NO-IMAGE'/>
<div className='card_content'>
<h2 className="card_title">{info.mission_name}</h2>
<p className='card_number'>Flight: {info.flight_number}</p>
<p className='card_description'>{info.details}</p>
</div>
</div>
)
}
Basically this is card, the data is from a web api. I want to make it so when I click on a card a whole new page shows with only that card data not other cards because they are iterated.

I suggest using useNavigate from react-router-dom. It is what I use for such things.
import { useNavigate } from 'react-router-dom'
const Card: React.FC = ({info}: any) => {
const navigate = useNavigate()
return (
<div className='card stacked featured'>
<img src={info.links.mission_patch} className='card_image' alt='NO-IMAGE'/>
<div className='card_content' onClick={() => navigate("/toThePageYouWantToNavigateTo")>
<h2 className="card_title">{info.mission_name}</h2>
<p className='card_number'>Flight: {info.flight_number}</p>
<p className='card_description'>{info.details}</p>
</div>
</div>
)
}

Import and render the Link component from react-router-dom.
import { Link } from 'react-router-dom';
...
const Card: React.FC = ({ info }: any) => {
return (
<div className='card stacked featured'>
<img src={info.links.mission_patch} className='card_image' alt='NO-IMAGE'/>
<Link
className='card_content'
to={`"/mission/${info.id}`} // <-- this is path you want to link to
>
<h2 className="card_title">{info.mission_name}</h2>
<p className='card_number'>Flight: {info.flight_number}</p>
<p className='card_description'>{info.details}</p>
</Link>
</div>
);
};
If you don't want to render an actual link/anchor tag into the DOM then import and use the useNavigate hook and add an onClick handler to the div element.
import { Link } from 'react-router-dom';
...
const Card: React.FC = ({ info }: any) => {
const navigate = useNavigate();
return (
<div className='card stacked featured'>
<img src={info.links.mission_patch} className='card_image' alt='NO-IMAGE'/>
<div
className='card_content'
onClick={() => navigate(`"/mission/${info.id}`)} // <-- this is path you want to link to
>
<h2 className="card_title">{info.mission_name}</h2>
<p className='card_number'>Flight: {info.flight_number}</p>
<p className='card_description'>{info.details}</p>
</div>
</div>
);
};

Related

Importing a filter variable from one Component to Another Component in REACT

So I have these 2 components:
First One MAIN PAGE
`
import {useEffect, useState} from 'react';
import Navbar from "./navbar";
import Modal from "./Modal";
import '../styles/home.css'
import FavoriteCrypto from "./favoriteCrypto";
export default function MainPage() {
const[data, setData] = useState([])
const[input, setInput] = useState("");
const [openModal, setOpenModal] = useState(false)
const [modalArr, setModalArr] = useState([])
const[favorites, setFavorites] = useState([])
const url = "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false"
useEffect(()=>{
fetch(url)
.then((res)=>{
return res.json()
})
.then((data)=>{
setData(data)
})
},[])
let searchBar = data.filter((e)=>{
return e.id.toLowerCase().includes(input.toLowerCase())
})
// add to favorite
function addToFav(id){
if(!favorites.includes(id)){
setFavorites(favorites.concat(id))
}
}
function openModalFunc(id) {
setOpenModal(true);
if(!modalArr.includes(id)) {
setModalArr(modalArr.concat(id))
}
}
function closeModalFunc(id) {
setOpenModal(false);
setModalArr([]);
}
let modalRender = data.filter(data => modalArr.includes(data.id));
let favoriteRender = data.filter(data => favorites.includes(data.id))
console.log(favoriteRender)
return(
<div>
<Navbar input={input} setInput={setInput}/>
<div className='general-info'>
<h4>Coin</h4>
<h4 className='p'>Price</h4>
<h4 className='c'>Change</h4>
<h4 className='mc'>Market Cap</h4>
<h4 className='s'>Supply</h4>
</div>
<Modal addFavorite = {addToFav} modalArr={modalRender} close = {closeModalFunc} open = {openModal}/>
{searchBar.map((e)=>(
<div
onClick={()=>{
openModalFunc(e.id);
}}
className='all_coins_wrapper'>
<div className='coins-wrapper'>
<div className='coins-label'>
<img src={e.image} alt=""/>
<div className='general_info'>
<div>{e.name}</div>
<div>{e.symbol.toUpperCase()}</div>
</div>
</div>
<p className='price-main'>${e.current_price}</p>
</div>
<div className='left-part'>
<p className='change'>{e.price_change_percentage_24h}</p>
<div className='marcap'>{e.market_cap}</div>
<div className='circ'>{e.circulating_supply}</div>
</div>
</div>
)
)}
</div>
)
}
SECOND ONE :
`
import React from "react";
import Navbar from "./navbar";
import MainPage from "./home";
export default function FavoriteCrypto({favorite}){
return(
<div>
</div>
)
}
I want to import these variable '
let favoriteRender = data.filter(data => favorites.includes(data.id))
from the first component to the second one in order to display on the second page the favoirite coins'
I tried to copy paste the code from the first component to the second component and to import the variable, but that didnt work. I am using react for a week now.So sorry if this question is already ask.But I cant solve this issue.
You don't need to export that variable in order to pass data between components. You can use props in-order to do so.
Here is the link to the docs.
And here is an example of doing so:
// COMPONENT
const MyNameComponent = (props) => <h1>{props.name}</h1>;
// USAGE
const App = () => {
const name = "John Doe";
return <MyNameComponent name={name} />
}
As a solution to your problem could be:
<FavoriteCrypto favourite={favouriteRender} />
and using it inside the component to display it. You can align the data according to your wish. Read the docs for more info 👍.

How to load a video in ReactPlayer when clicking a div that is fetching data from JSON file?

So I'm pretty much new in React/Web development and just can't figure it out regarding ReactPlayer.
I have a .JSON file with [ID, Question, URL] and I load the questions into divs. What I want is when I click the div(question) then the URL that is assigned to that question should load in the ReactPlayer..
This is how it looks so far:
import React, { useState } from "react";
import Questions from "../data/questions.json";
import style from "./Card.module.css";
import ReactPlayer from "react-player/youtube";
function Card() {
const handleClick = (item) => {
console.log(item);
};
return (
<div>
<div className={style.ViewContent}>
<div className={style.mainCard}>
{ListQuestions.map((ListItem, index) => {
return (
<div onClick={() => handleClick(ListItem.url)} key={index} className={style.Card}>
<h3 className={style.Titel}>{ListItem.question}</h3>
</div>
);
})}
</div>
<div className={style.VideoPlayer}>
<ReactPlayer url={handleClick.item} controls={true} />
</div>
</div>
</div>
);
}
export default Card;
I tested the click function and every time I click the question the console logs only the URL.
But how can the ReactPlayer get that URL and play the video?
I'm sorry for the bad coding.. still learning :)
I tried adding onSubmit on the div box so when clicking the div it should submit/load the link to the ReactPlayer... but thinking logically and then interpreting it kind of does not work.
I figured it out :D
import React, { useState } from "react";
import Questions from "../data/questions.json";
import style from "./Card.module.css";
import ReactPlayer from "react-player";
function Card() {
const [playUrl, setPlayUrl] = useState(""); ← here you could put the youtube link to show up when loading the page.
const [isPlaying, setIsPlaying] = useState(true);
return (
<div>
<div className={style.ViewContent}>
<div className={style.mainCard}>
{ListQuestions.map((ListItem, index) => {
return (
<div onClick={() => setPlayUrl(ListItem.url)} key={index} className={style.Card}>
<h3 className={style.Titel}>{ListItem.question}</h3>
</div>
);
})}
</div>
<div className={style.VideoPlayer}>
<ReactPlayer url={playUrl} controls={true} playing={isPlaying} />
</div>
</div>
</div>
);
}
export default Card;

Trying to pass a prop between pages using Link in NextJS

So I have a page with six Link tags which all need to redirect to one page with different props depending on which link is clicked. Here's how I'm passing props:
<Link href={{
pathname: '/products',
query: {category: 'Starters'}
}}>
<div class="container">
<div class="content">
<div class="content-overlay"></div>
<img class="content-image" src="/starters.png" />
<div class="content-details fadeIn-bottom">
<h3 class="content-title text-uppercase">Starters</h3>
</div>
</div>
<h3>Starters</h3>
</div>
</Link>
On the products page, here's how I'm reading these props:
export default function products(){
const router = useRouter()
const {id} = router.query
console.log(id)
return(
<>
<Navbar></Navbar>
<h1 className="text-center">{id}</h1>
<Footer></Footer>
</>
)
}
The problem here is that my id value is read as undefined or empty. I need to take this value, show it on my page and then send it to an API endpoint which will then use this string to execute a conditional SQL query.
Any idea as to why I'm getting an empty or undefined value and how to fix this?
Please try functional component instead like below. Hooks are used in functional components.
import React, { useState } from "react";
const Products = (props) => {
const [myId, setMyId] = useState<any>(null);
const [myCategory, setMyCategory] = useState<any>(null);
useEffect(() => {
console.log(props.router.query)
setMyId(props.router.query.id)
setMyCategory(props.router.query.category)
}, [props.router]);
return(<h1 className="text-center">{myId}</h1>);
}
Alternatively
import React, { useState } from "react";
import router from 'next/router';
const Products = () => {
const {id, category} = router.query
const [myId, setMyId] = useState<any>(null);
const [myCategory, setMyCategory] = useState<any>(null);
useEffect(() => {
if(!id) {
return;
}
console.log(id);
setMyId(id);
setMyCategory(category);
}, [id]);
return(<h1 className="text-center">{myId}</h1>);
}
Can you also modify your jsx a bit? For example
<Link href={{
pathname: '/products',
query: {id: 1, category: 'Starters'}
}}>
Starters
</Link>
<div class="container">
<div class="content">
<div class="content-overlay"></div>
<img class="content-image" src="/starters.png" />
<div class="content-details fadeIn-bottom">
<h3 class="content-title text-uppercase">Starters</h3>
</div>
</div>
</div>

how to send a parameter from a file to another in react

I'm building a pokedex website and I have pokemon cards with some data displayed in them from a JSON file and when you click on one of them you have a modal view that appears with more detailed data.
So in the modal view I want only the detailed data of the card I just clicked on it.
I have no idea how to do that if anyone can help, thanks.
This is Modal.tsx where I initialize my modal view, this where I want to get the pokemon name from Card.tsx (cf below) to be able to know which card was clicked :
import '../components/Modal.css';
import Data from '../pokemons.json';
import React from 'react';
export const Modal = ({showModal} : {showModal: boolean}) => {
return (
<>{showModal ? (
<div className="modal-back">
<div className="modal-container">
MODAL VIEW
</div>
</div>
): null}</>
);
};
This is Card.tsx where I handle the cards and where I call the modal view :
import Data from "../pokemons.json"
import '../components/Card.css'
import {FiThumbsUp} from "react-icons/fi"
import {useState} from 'react';
import {Modal} from './Modal';
function Card() {
const [showModal, setShowModal] = useState(false);
return(
<div className="cards">
{Data.map(card => {
return(
<div className="card-box" onClick={() => setShowModal(true)}>
<img src={card.img} alt="" />
<div className="text">
<div className="first-line">
<p className="id">{card.id}</p>
<p>{card.name}</p>
</div>
<div className="type-container">
{card.type.map((type, index) => {
return(
<div className="type" key={index}>
<p className={type}>{type}</p>
</div>
);
}) }
</div>
</div>
<div className="icon-circle">
<FiThumbsUp className="icon" color="#e5e5e5" size="18px"/>
</div>
</div>
);
}) }
<Modal showModal={showModal}></Modal>
</div>
);
}
export default Card;
You can pass selected card data as prop in the modal. You also need to update prop type as it only accepts one parameter.
Your Modal component will look like this:
interface ICard {
name: string,
...
}
interface props {
showModal: boolean;
card: ICard
}
export const Modal: FC<props> = ({showModal, card}) => {
return (
<>{showModal ? (
<div className="modal-back">
<div className="modal-container">
MODAL VIEW
</div>
<p>{card.name}</p>
</div>
): null}</>
);
};
You also need to update Card component to pass props. Make sure you're storing selected card data.
<Modal showModal={showModal} card={card} />

React Scroll to another page Not working react-scroll

I have a page where each component has scroll functionality. But it will come from another page.
Like on the Home page route is "/" I have set the scroll with
import { Link as Scrolllink, animateScroll as scroll } from 'react-scroll'
<Scrolllink
onClick={() => history.push('/services')}
to="DayCare"
spy={true}
smooth={true}
hashSpy={true}
isDynamic={true}
>
Day care
</Scrolllink>
<Scrolllink
onClick={() => history.push('/services')}
to="Office"
spy={true}
smooth={true}
hashSpy={true}
isDynamic={true}
>
Office
</Scrolllink>
Similar to this I have set for all the target elements.
Now In-service page I ave added the id of that target before that components
<div id="DayCare"> <DayCare /></div>
<div id="HomeApartment"> <HomeApartment/></div>
<div id="Office"> <Office/></div>
<div id="MoveInOut"> <MoveInOut/></div>
<div id="Construction"> <Construction/></div>
<div id="Airbnb"> <Airbnb/></div>
<div id="Carpet"> <Carpet/></div>
<div id="Infection"> <Infection/></div>
But I am pushing to the "/service" page, but not scrolled to target id:
If I click on On the link I going to a random component, not the one I have targeted.
How to fix this problem.
I had the same problem with my app and resolve it with async function and scroller from react-scroll:
import React from 'react';
import {scroller} from "react-scroll";
import {useHistory} from "react-router-dom";
const Nav = () => {
const history = useHistory();
const scrollTarget = (target) => scroller.scrollTo(target, {smooth: true, duration: 700});
const scrollToPage = async (target) => {
if (history.location.pathname !=='/') {
await history.push('/');
}
scrollTarget(target);
};
return (
<nav>
<div onClick={() => scrollToPage('about')}>About</div>
<div onClick={() => scrollToPage('info')}>Info</div>
<div onClick={() => scrollToPage('contact')}>Contact</div>
</nav>
);
}
export default Nav;
Maybe you can try the react-scrollable-anchor package https://www.npmjs.com/package/react-scrollable-anchor. For me it worked for navigating and scrolling from another page.

Categories