How to make this image clickable in React? - reactjs

I've tried using <a> and <Link to=""> as well but the image is not clickable. Now I've used click events still the image is not clickable. How to make this image clickable and redirect to a webpage?
import '../index.css';
import LinkedinLogo from '../assets/linkedin.png';
// import { Link } from "react-router-dom";
const SocialMedia = () => {
const link= () => {
window.location.href = "https://www.linkedin.com/";
}
return (
<div className="bottom absolute">
{/* <Link to="https://www.linkedin.com/"> */}
<img src={LinkedinLogo} alt="Linkedin logo" onClick={link}/>
{/* </Link> */}
</div>
);
}
export default SocialMedia;

Your code is workable.
What's problem did you get?
export default function App() {
const link = () => {
window.location.href = 'https://www.linkedin.com/'
}
return (
<div>
<div className='bottom absolute'>
<img
alt='Linkedin logo'
onClick={link}
src='https://picsum.photos/200/300'
/>
</div>
</div>
)
}

Related

How do I use the Use Navigate from React Router on a button that links to different pages?

I have a button that represents shop now that upon click it redirects you on different pages and the card elements have been mapped on external data.
I want this button to navigate to different pages kindly help.
const data =[
{
id:"Extensions",
Title:"Electrical Collections",
img:"/Assets/Electricals/Extlogo.png",
},
{
id:"Phone Accesorries",
Title:"Phone Accessories",
img:"/Assets/Phone/phoneacc.png",
},
{
id:"Homeware",
Title:"Homeware Collections",
img:"/Assets/Home/home.png",
},
]
function Home() {
let Navigate =useNavigate();
const handleElectricalPage = () =>{
Navigate("/extensionproduct")
}
<div className='cardContainer'>
{data.map((item )=>(
<card>
<div className='imageContainer'>
<img src={item.img} alt='Extension logo'/>
</div>
<div className='contentsContainer'>
<h2>{item.Title}</h2>
<div className='iconButtonContainer'>
<button onClick={handleElectricalPage}>Shop Now</button>
<ArrowForwardIcon className='arrowIcon'/>
</div>
</div>
Example from the react router https://reactrouter.com/docs/en/v6/api#usenavigate
navigate("../success", { replace: true });
You need to make an onClick handler (handleElectricalPage) dynamically, consider something like this.
function Home() {
let navigate =useNavigate();
return (
<div className='cardContainer'>
{data.map((item) => (
<card>
<button
onClick={() => navigate(`/externalProduct/${item.id}`)}
>
Shop Now
</button>
</card>
)}
</div>
}
You can also use Link which handles everything by itself
<Link to={`/externalProduct/${item.id}`}>
<button>Shop now</button>
</Link>
App.jsx
import { Routes, Route, Navigate } from "react-router-dom";
function App() {
return (
<div className="App">
<Routes>
<Route path="/" element={<Home />}>
<Route path="post/:id" element={<Detail />} />
</Route>
</Routes>
</div>
);
}
export default App;
Post.jsx
import React, { useState } from "react";
import {useNavigate} from 'react-router-dom'
export default function Post(props) {
const navigate = useNavigate()
{props.posts.map((post) => {
return (
<div className="post__container" key={post.id}>
<h4>
{post.id} {post.title}
</h4>
<p>{post.body}</p>
<button onClick={() => {return navigate(`${post.id}`)}}>Detail</button>
</div>
);
})}
}
Detail.jsx
import axios from 'axios'
import React, {useEffect, useState } from 'react'
import {useParams} from 'react-router'
export default function Detail (props) {
const params = useParams()
const [posts, setPosts] = useState({})
async function getById(id) {
const response = await axios.get("https://jsonplaceholder.typicode.com/posts/" + id)
setPosts(response.data)
}
useEffect(() => {
getById(params.id)
}, [params.id])
return (
<div>
<h2>Detail page: {params.id}</h2>
<h4>{posts.title}</h4>
<h5>{posts.body}</h5>
</div>
)
}

How to display Splash screen in reactjs

I have two codes for Splash.jsx and one for homepage.jsx. All I want is to display the Splash screen once the Homepage is not in use, but I have no idea how to integrate the splash screen with the Homepage and set the timer, so the splash screen is displayed once I don't use Homepage. It would be great to help me out with showing the splash screen once the Homepage is not in use.
Homepage.jsx
import React from 'react';
import Card from '../Card/Card'
import img2 from '../../Assets/AutoLoan.png'
import img3 from '../../Assets/KYC.png'
import img4 from '../../Assets/VIsa.png'
import './Homepage.css'
import {
Swiper,
SwiperSlide
}
from 'swiper/react';
import 'swiper/css';
import { Navigation } from 'swiper';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import 'swiper/css/scrollbar';
import { Link } from 'react-router-dom';
const Homepage= () => {
return (
<div>
<div className="background">
<div className="welcome__heading">
<h1>Welcome!!</h1>
</div>
<div className= "customer__support">
<h2>We are here for customer service.</h2>
</div >
<div className="swiper_container">
<Swiper
modules={[Navigation]}
navigation
spaceBetween={10}
slidesPerView={3}
onSwiper={(swiper) => console.log(swiper)}
onSlideChange={() => console.log('slide change')}
loop={true}
>
<SwiperSlide>
<Link to="AutoLoan">
<Card imgsrc={img2} alt="AutoLoan" title="Auto Loan" />
</Link>
</SwiperSlide>
<SwiperSlide>
<Link to="KYC">
<Card imgsrc={img3} alt="KYC" title="KYC Form" />
</Link>
</SwiperSlide>
<SwiperSlide>
<Link to="Debit">
<Card imgsrc={img4} alt="Visa" title="Visa Debit Card" />
</Link>
</SwiperSlide>
</Swiper>
</div>
<div ClassName="button">
<Link to = "Location">
<button className = "btn1">
<i className = "fa fa-map"></i>
</button>
</Link>
<Link to = "Calculator">
<button className = "btn2">
<i className = "fa fa-calculator"></i>
</button>
</Link>
</div>
</div>
</div>
);
}
export default Homepage
Splash.jsx
import React from 'react';
import './Splash.css'
import img2 from '../../Assets/Header.png'
import img8 from '../../Assets/hand.svg'
const Splash = () => {
return (
<div>
<div className="bg2">
<div className="header__body">
<div className="header__left">
<div className="header__left__image">
<img src = {img2} alt="Header"/>
</div>
<h1 >Laxmi Bank</h1>
</div>
<div className="header__right">
<h1 >23℃/11:00AM</h1>
</div>
</div>
</div>
<div className="splash">
<h1>TAP HERE</h1>
<div className= "blink">
<img src = {img8} alt = "taphand" />
</div>
</div>
</div>
);
};
export default Splash;
The splash screen should appear after 2 sec of not using Homepage, and once we tap on the splash screen the Homepage should appear again and once it is idle the splash screen should appear and vice versa. and I have no idea how to set the timer and control this component. So, it would be good if someone would help me out.
You need to create a idle timer to trigger after inactivity of the
user in Homepage
When setTimeout triggers the callback it will mount the Splash
Once Splash is mounted, click on the Link tag says TAP HERE back to redirect to home
Homepage -
(path = "/home")
import React,{ useEffect } from "react";
import { useNavigate } from "react-router-dom";
const Homepage= () => {
let navigate = useNavigate();
useEffect(() => {
//Idle timer
let timerId;
const resetTimer = () => {
clearTimeout(timerId);
timerId = setTimeout(() => {
navigate("/splash");
}, 30 * 1000); //30 sec idle time
};
document.addEventListener("keydown", resetTimer);
document.addEventListener("mousemove", resetTimer);
return () => {
clearTimeout(timerId);
document.removeEventListener("keydown", resetTimer);
document.removeEventListener("mousemove", resetTimer);
};
}, []);
}
Splash - (path = "/splash")
const Splash = () => {
return <div>
...
<Link to='/home'>TAP HERE</Link>
</div>
}
You can use react-idle-timer package. A working solution exists here

I am am trying to link the image click to a new product page

I have created a product card to show products on my homepage. I have created and product screen to display the single product and allow the user to add to cart. When i click on the on the image the page refreshes but there is no product on the screen. I have console loged and confirmed that the property id is undefined.
import React from "react";
import { Link } from "react-router-dom";
import Rating from "./rating";
export default function Product(props) {
const { product } = props;
console.log(product._id);
return (
<div key={product._id} className="card">
<Link to={`api/products/${product._id}`}>
<img className="medium" src={product.image} alt={product.name} />
</Link>
<div className="card-body">
<Link to={`/product/${product._id}`}>
<h2>{product.name}</h2>
</Link>
<Rating
rating={product.rating}
numReviews={product.numReviews}
></Rating>
<div className="price">${product.price}</div>
</div>
</div>
);
}
``` Product component
import React from 'react'
import { Link } from 'react-router-dom';
import Rating from './rating';
import { useEffect } from 'react';
export default function Product(props) {
const { product } = props;
useEffect(()=>{
console.log('ooooh, am I undefined?');
console.log(product);
},[product]);
if(product) {
At a guess, you are passing the prop through from somewhere else into this component from some API call or async function.
What is happening, is its going from undefined to defined as part of some API call or something, and as a result, your getting undefined in your component on first render. You need to do something to keep a track of your changing state.
You'll need to do something around 'loading' state for that API call, which is outside of the component code that you've posted. In other words, your example isn't a complete picture of your code, and as such, it's hard to give you a complete answer.
Try this for debugging that assumption.
import {useState} from 'react';
export default function Product(props) {
const { product } = props;
useEffect(()=>{
console.log('ooooh, am I undefined?');
console.log(product);
},[product]);
if(product) {
return (
<div key={product._id} className="card">
<Link to=
{`api/products/${product._id}`}>
<img
className="medium"
src={product.image}
alt={product.name}
/>
</Link>
<div className="card-body">
<Link to=
{`/product/${product._id}`}>
<h2>{product.name}</h2>
</Link>
<Rating
rating={product.rating}
numReviews={product.numReviews}
></Rating>
<div
className="price">${product.price}</div>
</div>
</div>
)}
}else{
return <p>Product null</p>
}
'''
export default function HomeScreen() {
const [products, setProducts] = useState([]);
useEffect(() => {
const fecthData = async () => {
try {
const { data } = await axios.get(`https://fakestoreapi.com/products`);
setProducts(data);
} catch (err) {
console.log("Server responded with error",err);
}
};
fecthData();
}, []);
return (
<div>
<div className="row center">
{products.map((product) => (
<Product key={product._id} product={product}></Product>
))}
</div>
</div>
);
}

Folders in the sidebar component (react.js dashboard) doesn't always open when I click them

Story
I'm using this react.js template http://skote-v-light.react.themesbrand.com/email-read from https://themeforest.net/item/skote-react-admin-dashboard-template/26318700 for building my react app.
I use and modify the sidebar component from the template and name it Sidebar.js.
There is SidebarContent.js for building the content inside the sidebar.
There is MenuComponent.js inside SidebarContent.js for building the menu inside the sidebar.
MenuComponent.js takes a list from menuList.js and renders it.
There are two dummy pages which are Route/Summary page (Summary.js) and Payload page (Payload.js) inside the Sidebar. I combine them all inside PageWithSidebar.js.
Question
Why don't always the ABC, DEF, etc folders in the sidebar open when I click them?
Ideal Condition I Wanted
Every folder (ABC, DEF, etc) inside the sidebar always opens when I click one of them.
Actual Condition
Please watch this demo to understand the context: https://drive.google.com/file/d/1Lig1SKKRtyRqxWm_OYNkuQennrytV0jo/view?usp=sharing
Steps:
Click the Route/Summary option inside the ABC folder -> Summary page is shown (as I wanted)
Click the Payload option inside the ABC folder -> Payload page is shown (as I wanted)
Click another Route/Summary option inside the ABC folder -> Summary page is shown (as I wanted)
Close the ABC folder -> The folder closes (as I wanted)
Click the DEF folder -> The folder doesn't open (not I wanted)
There is no error or warning log in the browser console.
Code
PageWithSidebar.js:
import React from 'react'
import { Route, Switch } from "react-router-dom";
// COMPONENTS
import Sidebar from '../../components/Menu/Sidebar/Sidebar'
// PAGES
// ROUTE
import Summary from '../Routes/Summary/Summary'
// PAYLOAD
import Payload from '../Payload/Payload'
const PageWithSidebar = () => {
return(
<div id="layout-wrapper">
<Sidebar/>
<div className="main-content">
<Switch>
{/* ROUTE */}
<Route path="/route/summary/location=:locationName">
<Summary/>
</Route>
<Route path="/payload/location=:locationName">
<Payload/>
</Route>
</Switch>
</div>
</div>
)
}
export default PageWithSidebar
Sidebar.js:
import React from "react"
import { Link } from "react-router-dom"
// COMPONENTS
import SidebarContent from './SidebarContent'
// IMAGES
import IconClose from '../../../images/icons/close.svg'
import IconOpen from '../../../images/icons/open.svg'
const Sidebar = () => {
const toogleSidebar = () => {
var body = document.body;
body.classList.toggle("vertical-collpsed");
body.classList.toggle("sidebar-enable");
}
return (
<React.Fragment>
<div className="vertical-menu">
<div className="navbar-brand-box">
<Link to='/' className="logo logo-dark">
{/* SIDEBAR IS CLOSED */}
<span className="logo-sm">
{/* TOOGLE SIDEBAR BUTTON */}
<img src={IconOpen} alt='' className='icon-open' onClick={toogleSidebar}/>
</span>
{/* SIDEBAR IS OPEN */}
<span className="logo-lg sidebar-is-open-container">
{/* TOOGLE SIDEBAR BUTTON */}
<img src={IconClose} alt='' className='icon-close' onClick={toogleSidebar}/>
</span>
</Link>
</div>
{/* SIDEBAR CONTENT */}
<SidebarContent />
<div className="sidebar-background"></div>
</div>
</React.Fragment>
)
}
export default Sidebar
SidebarContent.js:
import PropTypes from "prop-types"
import React, { useEffect, useRef, useState } from "react"
import { withRouter, Link, useLocation } from "react-router-dom"
// Import Scrollbar
import SimpleBar from "simplebar-react"
// MetisMenu
import MetisMenu from "metismenujs"
//i18n
import { withTranslation } from "react-i18next"
// COMPONENTS
import MenuComponent from './MenuComponent'
// IMAGES
import IconFolderGray from '../../../images/icons/folder-gray.svg'
import IconFolderRed from '../../../images/icons/folder-red.svg'
import IconLogout from '../../../images/icons/logout.svg'
// MENU ITEMS
import menuList from './menuList/menuList'
// STYLES
import './styles.scss'
import logoutUser from '../../../utils/authentication/logOut'
const SidebarContent = props => {
// MY OWN CODE SECTION
const location = useLocation()
const pathName = location['pathname']
let locationName = ''
if(pathName.includes('route')) {
locationName = pathName.split('/')[3].replace('location=', '')
}
else {
locationName = pathName.split('/')[2].replace('location=', '')
}
// console.log('SidebarContent, locationName:', locationName)
// TEMPLATE CODE SECTION
const ref = useRef()
useEffect(() => {
const pathName = props.location.pathname
const initMenu = () => {
new MetisMenu("#side-menu")
let matchingMenuItem = null
const ul = document.getElementById("side-menu")
const items = ul.getElementsByTagName("a")
for (let i = 0; i < items.length; ++i) {
if (pathName === items[i].pathname) {
matchingMenuItem = items[i]
break
}
}
if (matchingMenuItem) {
activateParentDropdown(matchingMenuItem)
}
}
initMenu()
}, [props.location.pathname])
useEffect(() => {
ref.current.recalculate()
})
function scrollElement(item) {
if (item) {
const currentPosition = item.offsetTop
if (currentPosition > window.innerHeight) {
ref.current.getScrollElement().scrollTop = currentPosition - 300
}
}
}
function activateParentDropdown(item) {
item.classList.add("active")
const parent = item.parentElement
const parent2El = parent.childNodes[1]
if (parent2El && parent2El.id !== "side-menu") {
parent2El.classList.add("mm-show")
}
if (parent) {
parent.classList.add("mm-active")
const parent2 = parent.parentElement
if (parent2) {
parent2.classList.add("mm-show") // ul tag
const parent3 = parent2.parentElement // li tag
if (parent3) {
parent3.classList.add("mm-active") // li
parent3.childNodes[0].classList.add("mm-active") //a
const parent4 = parent3.parentElement // ul
if (parent4) {
parent4.classList.add("mm-show") // ul
const parent5 = parent4.parentElement
if (parent5) {
parent5.classList.add("mm-show") // li
parent5.childNodes[0].classList.add("mm-active") // a tag
}
}
}
}
scrollElement(item);
return false
}
scrollElement(item);
return false
}
// MY OWN CODE SECTION
const itemList = ['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQR']
const [ selectedItem, setSelectedItem ] = useState(itemList.indexOf(locationName.toUpperCase()))
return (
<React.Fragment>
<SimpleBar style={{ maxHeight: "100%" }} ref={ref}>
<div id="sidebar-menu">
<ul className="metismenu list-unstyled sidebar-content-menu-container" id="side-menu">
{/* TITLE */}
<li className="menu-title sidebar-content-site-profile-title">Dummy Locations</li>
{/* ITEMS */}
{
itemList.map((item, index) => (
<li
key={index}
className={selectedItem === index ? 'sidebar-content-dropdown-selected' : 'sidebar-content-dropdown'}
// onClick={() => setSelectedItem(index)}
>
{/* TITLE */}
<Link to="/" className="has-arrow dropdown-link">
{/* FOLDER ICON */}
<img
src={selectedItem === index ? IconFolderRed : IconFolderGray}
alt=''
className='bx sidebar-content-icon-folder-gray'
/>
{/* TEXT */}
<span className='dropdown-span'>
{item}
</span>
</Link>
{/* MENU COMPONENT*/}
<ul className="sub-menu" aria-expanded="false">
<div className='border-line'></div>
<MenuComponent list={menuList} pathName={item.toLowerCase()}/>
</ul>
</li>
))
}
{/* PROFILE */}
<li className='sidebar-content-single-item-container'>
<Link to='/'>
<div onClick={logoutUser}>
<img src={IconLogout} alt='' className='sidebar-content-icon-single-item'/>
<span className='sidebar-content-span-single-item'>Logout</span>
</div>
</Link>
</li>
</ul>
</div>
</SimpleBar>
</React.Fragment>
)
}
SidebarContent.propTypes = {
location: PropTypes.object,
t: PropTypes.any,
}
export default withRouter(withTranslation()(SidebarContent))
MenuComponent.js:
import React, { useState } from 'react'
import { Link } from "react-router-dom"
const MenuComponent = (props) => {
const [ selectedItem, setSelectedItem ] = useState(0)
return(
props['list'].map((item, index) => (
<li
key={index}
onClick={() => setSelectedItem(index)}
>
<Link
to={`${item['path']}/location=${props['pathName']}`}
className='menu-component-root'
>
{/* CIRCLE */}
<div className={selectedItem === index ? 'circle-selected' : 'circle'}></div>
{/* TEXT */}
<p className='text'>
{item['text']}
</p>
</Link>
</li>
))
)
}
export default MenuComponent
menuList.js:
const menuList = [
{
path: '/route/summary',
text: 'Route/Summary'
},
{
path: '/route/summary',
text: 'Route/Summary'
},
{
path: '/payload',
text: 'Payload'
},
{
path: '/route/summary',
text: 'Route/Summary'
},
{
path: '/route/summary',
text: 'Route/Summary'
},
{
path: '/route/summary',
text: 'Route/Summary'
},
{
path: '/route/summary',
text: 'Route/Summary'
}
]
export default menuList
Summary.js:
import React from "react"
import { Row, Col } from "reactstrap"
// STYLES
import './styles.scss'
const Summary = () => {
return (
<React.Fragment>
<div className="container-fluid route-summary-root">
<Row>
<Col className="col-12">
{/* TOP CONTAINER */}
<div className='top-container'>
{/* LEFT CONTAINER */}
<div className='top-left-container'>
<h3 className='title'> Route/Summary Page</h3>
</div>
</div>
</Col>
</Row>
</div>
</React.Fragment>
)
}
export default Summary
Payload.js:
import React from "react"
import { Row, Col } from "reactstrap"
// STYLES
import './styles.scss'
const Payload = () => {
return (
<React.Fragment>
<div className="container-fluid payload-root">
<Row>
<Col className="col-12">
{/* TOP CONTAINER */}
<div className='top-container'>
{/* LEFT CONTAINER */}
<div className='top-left-container'>
<h3 className='title'>Payload Page</h3>
</div>
</div>
</Col>
</Row>
</div>
</React.Fragment>
)
}
export default Payload
Note: let me know if the question is confusing. I will try to update it.

How to close sidenav when I click anywhere of the page in react js

**Nav-header.js**
The sidebar should not collapse when I am clicking outside of the page in react js. Please help with that. this is the code I wrote for the side menu. I am a beginner at the react js. Please help
import React, { useState } from 'react'
import * as FaIcons from 'react-icons/fa'
import * as AiIcons from 'react-icons/ai'
import { Link } from 'react-router-dom'
import { SidebarData } from './SidebarData'
import './Navbar.css'
import { IconContext } from 'react-icons'
const Header = () => {
const [sidebar, setsidebar] = useState(false)
const showSideBar = () => setsidebar(!sidebar)
return (
<>
<IconContext.Provider value={{ color: '#1D1D1D' }}>
<div className='navbar'>
<Link to="#" className='menu-bars'>
<FaIcons.FaBars onClick={showSideBar} color="#009540"/>
</Link>
<span className="meny">Meny</span>
</div>
<nav className={sidebar ? 'nav-menu active' : 'nav-menu' } >
<ul className='nav-menu-items' onClick={showSideBar}>
<li className='navbar-toggle'>
<Link to="#" className='menu-bars-logo'>
<AiIcons.AiOutlineClose/>
</Link>
</li>
{SidebarData.map((item, index) => {
return (
<li key={index} className={item.cName}>
<Link to={item.path}>
<span>{item.title}</span>
</Link>
</li>
)
})}
</ul>
</nav>
</IconContext.Provider>
</>
)
}
export default Header
You can use onblur, in react it would look like
return (
<div onBlur={() => {
... do something like setState
}}>
)

Resources