Is there any way to use mobile image different from the desktop mode in react slick slider? I can use display none for breakpoints but what I want to learn, Is there any different way to do it?
const Hero = () => {
const classes = useStyle();
const { push } = useRouter();
const [sliderState, setSliderState] = useState(heroSliderData);
const [my_swiper, set_my_swiper] = useState({});
return (
<section className={classes.section}>
<Grid style={{ width:"100%", padding: "0px" }}>
<Swiper
loop={true}
navigation={true}
onInit={(ev) => {
set_my_swiper(ev);
}}
>
{sliderState.map(({ id, mainheading, mainheading2, subheading, subheading2, buttontext, image }) => (
<SwiperSlide key={id}>
<Grid item className={classes.hero}>
<img className={classes.heroimg} src={image} style={{ position:"relative"}} />
<Grid item xs={12} style={{ position:"absolute", top:"30%", left:"0", right:"0", textAlign: "center" }}>
<Typography variant="h1" className={classes.h1}>
{mainheading}<br />
{mainheading2}
</Typography>
</Grid>
<Grid item xs={12} style={{ position:"absolute", top:"42%", left:"0", right:"0", textAlign: "center" }}>
<Typography variant="h2" className={classes.h2}>
{subheading}
<br/>
{subheading2}
</Typography>
</Grid>
<Grid item xs={12} style={{ position:"absolute", top:"52%", left:"0", right:"0", textAlign: "center" }}>
<Button
variant="contained"
onClick={() => push("/teklif-al")}
className={classes.teklifal}
>
{buttontext}
</Button>
</Grid>
</Grid>
</SwiperSlide>
))}
</Swiper>
</Grid>
</section>
);
};
This is my code that I am working on it
Have you tried to use an IF clause to show and hide images?
See docs of React Slick.
import React, { Component } from "react";
import Slider from "react-slick";
export default class MultipleItems extends Component {
render() {
const settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 3,
slidesToScroll: 3
};
return (
<div>
<h2> Multiple items </h2>
<Slider {...settings}>
<div>
<h3>1</h3>
</div>
<div>
<h3>2</h3>
</div>
<div>
<h3>3</h3>
</div>
<div>
<h3>4</h3>
</div>
<div>
<h3>5</h3>
</div>
<div>
<h3>6</h3>
</div>
<div>
<h3>7</h3>
</div>
<div>
<h3>8</h3>
</div>
<div>
<h3>9</h3>
</div>
</Slider>
</div>
);
}
}
And modify like this:
import React, { Component } from "react";
import Slider from "react-slick";
export default class MultipleItems extends Component {
const showOnMobile = document.innerWidth < 769;
render() {
const settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 3,
slidesToScroll: 3
};
return (
<div>
<h2> Multiple items </h2>
<Slider {...settings}>
{showOnMobile &&
<div>
<h3>1</h3>
</div>
}
<div>
<h3>2</h3>
</div>
<div>
<h3>3</h3>
</div>
<div>
<h3>4</h3>
</div>
<div>
<h3>5</h3>
</div>
<div>
<h3>6</h3>
</div>
<div>
<h3>7</h3>
</div>
<div>
<h3>8</h3>
</div>
<div>
<h3>9</h3>
</div>
</Slider>
</div>
);
}
}
Related
I have multiple rendered components on a page. When I click on one I want to navigate to a new page with all of the information specific to that component. What I need is:
OnClick -> Identify gameId variable
Using that gameID run a query against an API endpoint
Take the rendered data from the API and display it on a new page with route /nhl/:gameId
Example screenshot of /NHL page with different components.
/NHL Route
I have this existing Scores component:
function Scores(props) {
const navigate = useNavigate('/');
const handleClick = () => {
let path = '/' + {gameId};
navigate(path);
}
return (
<Card sx={{ Height: 50, padding: .25, margin: 3 }}>
<CardActionArea onClick={handleClick}>
<div className = "">
<CardContent sx={{ width: 200 }}>
<Stack direction="row" spacing={2}>
<Typography component="div" variant="h6">{props.gameStatus}</Typography>
<Typography>{props.gameDateandTime}</Typography>
</Stack>
<Stack direction="row" spacing={2}>
<Typography fontSize={14} sx={{ paddingTop: 1, paddingBottom: 1 }}>{props.awayTeam}</Typography>
<Typography fontSize={14} sx={{ paddingTop: 1, paddingBottom: 1 }}>{props.awayPoints}</Typography>
</Stack>
<Typography>#</Typography>
<Stack direction="row" spacing={2}>
<Typography fontSize={14} sx={{ paddingTop: 1, paddingBottom: 1 }}>{props.homeTeam}</Typography>
<Typography fontSize={14} sx={{ paddingTop: 1, paddingBottom: 1 }}>{props.homePoints}</Typography>
</Stack>
</CardContent>
</div>
</CardActionArea>
</Card>
)
}
export default Scores;
The Scores.js component above is rendered in the NHL route from the screenshot:
function NHL(){
var date = year + "-" + month + "-" + day;
const [scores, setScores] = useState([{ }]);
useEffect(() => {
let url = "http://localhost:3001/schednhl";
fetch(url).then(res => {
if(res.ok) {
return res.json()
}
}).then(jsonRes => setScores(jsonRes));
}, []);
return (
<div className='Home'>
<Banner />
<Typography variant="h3" align="center" sx={{ paddingTop: 5 }}>Live Games</Typography>
<hr className="lineRow"></hr>
<Stack direction="row" spacing={2}>
<div className="scroll-box">
<div className="scroll-box-wrapper">
<div className="scroll-box-container" role="list">
{scores.map((score, index) => {
if(score.gameDate === date && score.gameStatus === "closed" || score.gameStatus === "inprogress")
return (
<Scores
className="scroll-box-item"
role="listitem"
key={index}
id={index}
gameDate={score.gameDate}
gameStatus={score.gameStatus === "closed" ? "Final" : "Live" }
homeTeam={score.homeTeam}
homePoints={score.homePoints}
awayPoints={score.awayPoints}
awayTeam={score.awayTeam}
/>
);
})}
</div>
</div>
</div>
</Stack>
<h3 className="home-header" style={{paddingTop: 10 }}>Upcoming Games</h3>
<hr className="lineRow" style={{ }}></hr>
<Grid container spacing={3} direction="row" justifyContent="flex-start">
{scores.map((score, index) => {
if(score.gameDate === date && score.gameStatus === "scheduled" || score.gameStatus === "upcoming")
return (
<Scores
className="scroll-box-item"
role="listitem"
key={index}
id={index}
time={score.gameDateandTime}
gameStatus={score.gameStatus === "scheduled" ? "Upcoming" : ""}
homeTeam={score.homeTeam}
homePoints={score.homePoints}
awayPoints={score.awayPoints}
awayTeam={score.awayTeam}
/>
);
})}
</Grid>
</div>
);
}
export default NHL;
How can I access the gameId from the NHL function and use that in my Score component?
I have three components called blog cards that are rendered with an image and text. Depending on how long the text is the cards are of different heights. I want to render them, then get the tallest one, and sort of re-render them, so they are all the same height.
Here is the Page
import * as React from 'react'
import { SocialIconRow } from '#/components/social-icons'
import BlogPostCard from '#/components/BlogCard'
import Image from 'next/image'
import { useState, useEffect } from 'react'
import { FixedSizeList } from 'react-window'
function BlogPostCardsList({ cards }) {
const tallestCardHeight = useMemo(() => {
return Math.max(...cards.map(card => card.height))
}, [cards])
return (
<FixedSizeList
itemCount={cards.length}
itemSize={tallestCardHeight}
width={'100%'}
height={'100%'}
>
{({ index, style }) => <BlogPostCard style={style} {...cards[index]} />}
</FixedSizeList>
)
}
export default function MyComponent(props) {
const [cardHeight, setCardHeight] = useState(null);
const [maxHeight, setMaxHeight] = useState(0);
useEffect(() => {
const calculateHeight = () => {
const cards = document.querySelectorAll('.blog-post-card');
let heights = [];
cards.forEach(card => {
heights.push(card.clientHeight);
});
setMaxHeight(Math.max(...heights));
}
calculateHeight();
setCardHeight(maxHeight);
}, []);
return (
<>
<div className="container mx-auto flex flex-col">
<div className="container mx-auto flex">
<div className="w-1/2 pr-4">
<div className="text-4xl font-bold">Mike Borman</div>
<div className="text-lg mt-2">Writer, Content Creator and Developer on Cardano</div>
</div>
<div className="w-1/2 flex flex-col justify-center">
<div className="max-h-48 max-w-48 mx-auto my-auto">
<Image
src="/images/myfaceppgray.png"
alt="Picture of the author"
className="max-h-48 max-w-48"
width="150"
height="150"
unoptimized={true}
/>
</div>
<div className="mt-4">
<SocialIconRow className="social-icon-row" />
</div>
</div>
</div>
<div className="mt-8">
<div className="text-3xl font-bold">Featured Blogs</div>
<div className="grid grid-cols-3 gap-4 h-full mt-4 align-items-stretch">
<div style={{height: cardHeight}}>
<BlogPostCard
title="The Hydra Protocol Family — Scaling and Network Optimization for the Cardano Blockchain"
slug="the-hydra-protocol-family-scaling-and-network-optimization-for-the-cardano-blockchain"
imageslug="/images/hydra.png"
className="blog-post-card"
/>
</div>
<div style={{height: cardHeight}}>
<BlogPostCard
title="Ouroboros, A deep dive for non PhDs"
slug="ouroboros-a-deep-dive-for-non-phd"
imageslug="/images/ourobouros.png"
className="blog-post-card"
/>
</div>
<div className="h-full row-auto" style={{height: cardHeight}}>
<BlogPostCard
title="Ouroboros, A deep dive for non PhDs"
slug="ouroboros-a-deep-dive-for-non-phd"
imageslug="/images/ourobouros.png"
className="blog-post-card"
/>
</div>
</div>
</div>
</div>
</>
)
}
Here is the Card component:
import React from 'react'
import Link from 'next/link'
import Image from 'next/image'
function BlogPostCard(props) {
const { title, slug, imageslug } = props
return (
<Link href={`/blog/${slug}`}>
<a className="block flex flex-col justify-between rounded-md border-2 border-teal-400 transition-all duration-300 ease-in-out hover:scale-105 hover:shadow-lg">
<img className="rounded-t-md h-48 w-full object-cover" src={imageslug} alt="blog post cover" />
<span className="text-white text-2xl p-4">{title}</span>
</a>
</Link>
)
}
export default BlogPostCard
I tried dynamically rendering them then setting them, btw I have no idea really what Im doing there.
You actually have all but one class already to do this entirely in CSS. Just add h-full to your a tag inside the BlogPostCard component's Link. Then you can get rid of all of the JS. Optionally, you could also remove the justify-between or change it to justify-stretch so that the titles of the blog posts are directly beneath of the post cover images.
In the demo below, you can see the result by clicking run code snippet. Also, if you're upgrading to NextJS 13, it's worth noting that you no longer need (and in fact can't have) an a tag as a child of Link. I'd suggest using article as I've done below, which will be more semantically correct anyway.
function BlogPage({posts}) {
return (
<main className="container mx-auto my-8">
<div className="flex gap-4">
<div className="w-1/2">
<h1 className="text-4xl font-bold">Mike Borman</h1>
<h2 className="text-lg mt-2">
Writer, Content Creator and Developer on Cardano
</h2>
</div>
<div className="w-1/2 flex flex-col justify-center items-center">
<span className="w-[150px] h-[150px] bg-neutral-300 rounded-full grid place-content-center">author img here</span>
<span>social row here</span>
</div>
</div>
<section className="mt-8">
<header>
<h2 className="text-3xl font-bold">Featured Blogs</h2>
</header>
<div className="grid grid-cols-3 gap-4 h-full mt-4 align-items-stretch">
{posts.map((post) => (
<BlogPostCard key={post.id} {...post} />
))}
</div>
</section>
</main>
)
}
function BlogPostCard({ slug, imageslug, title,}) {
return (
<Link href={`/blog/${slug}`}>
<article className="flex flex-col justify-stretch h-full rounded-md border-2 border-teal-400 bg-neutral-600 transition-all duration-300 ease-in-out hover:scale-105 hover:shadow-lg">
<img
className="rounded-t-md h-48 w-full object-cover"
src={imageslug}
alt="blog post cover"
/>
<span className="text-white text-2xl p-4">{title}</span>
</article>
</Link>
)
}
/* Stubbing out next/link here since I can't run NextJS in code snippets */
function Link({ href, children, className }) {
return (
<a href={href} className={className}>
{children}
</a>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<BlogPage posts={[
{
id: 1,
title: 'The Hydra Protocol Family — Scaling and Network Optimization for the Cardano Blockchain',
slug: 'the-hydra-protocol-family-scaling-and-network-optimization-for-the-cardano-blockchain',
imageslug: 'https://d3lkc3n5th01x7.cloudfront.net/wp-content/uploads/2019/05/15233606/700-X-394.png',
},
{
id: 2,
title: 'Ouroboros, A deep dive for non PhDs',
slug: 'ouroboros-a-deep-dive-for-non-phd',
imageslug: 'https://www.almaviva.it/dam/jcr:6212e8ef-1ed6-40e2-a75f-b6fa7c814662/Blockchain_1280x720.jpg',
},
{
id: 3,
title: 'How Blockchain Is Used',
slug: 'how-blockchain-is-used',
imageslug: 'https://imageio.forbes.com/specials-images/imageserve/5f2a32ee3b52675a453e2881/Fascinating-Examples-Of-How-Blockchain-Is-Used-In-Insurance--Banking-And-Travel/960x0.jpg?format=jpg&width=960',
},
]} />
);
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>
<div id="root"></div>
Uncaught TypeError: Cannot read properties of null (reading 'imageLink')
The above error occurred in the <ProductMoreDetails> component:
This Products page Display all the products in the database. When I click on any product card it will redirects to the more details page of that product. First time it loads without any issue and when I refresh the page or backward the page it will disappear all the content in the page.
ProductMoreDetails.js
import Navbar from "../components/Navbar";
import { useProductsContext } from "../hooks/useProductsContext";
import { useParams } from "react-router-dom";
import { useEffect } from "react";
//setproducts
const ProductMoreDetails = () => {
const {products,dispatch} = useProductsContext();
const {id} = useParams();
useEffect(() => {
const fetchProducts = async () => {
const response = await fetch(`/api/products/${id}`)
const json = await response.json()
if (response.ok) {
dispatch({type: 'SET_PRODUCTS', payload: json})
}
}
fetchProducts()
},[dispatch,id])
return (
<div className="moredetails">
<Navbar/>
<br /><br />
<div className="details">
<img className="productImage" src={products.imageLink} alt="productImage" />
<div className="details-section"></div>
<div className="row section1">
<div className="col-lg-8">
</div>
<div className="col-lg-2">
<button className="btn btn-primary addnew">Add to Cart</button>
</div>
</div>
<div className="row section1">
<div className="col-lg-8">
<h1>{products.productName}</h1>
</div>
<div className="col-lg-2">
<h1>Rs. {products.price}</h1>
</div>
</div>
<div className="section1">
<hr />
<h1>Product Details</h1>
<br />
<div className="row">
<div className="col-lg-6">
<div className="row">
<div className="col-lg-6">
<h6>Category</h6>
</div>
<div className="col-lg-6">
<p>{products.category}</p>
</div>
</div>
</div>
<div className="col-lg-6">
<div className="row">
<div className="col-lg-6">
<h6>Brand</h6>
</div>
<div className="col-lg-6">
<p>{products.brand}</p>
</div>
</div>
</div>
</div>
<br />
<div className="row">
<div className="col-lg-6">
<div className="row">
<div className="col-lg-6">
<h6>Model</h6>
</div>
<div className="col-lg-6">
<p>{products.model}</p>
</div>
</div>
</div>
<div className="col-lg-6">
<div className="row">
<div className="col-lg-6">
<h6>Year</h6>
</div>
<div className="col-lg-6">
<p>{products.year}</p>
</div>
</div>
</div>
</div>
<br />
<div className="row">
<div className="col-lg-6">
<div className="row">
<div className="col-lg-6">
<h6>Features</h6>
</div>
<div className="col-lg-6">
<p>{products.features}</p>
</div>
</div>
</div>
</div>
<hr />
<div className="section2">
<h1>Product Description</h1>
</div>
<p>
{products.description}
</p>
</div>
</div>
</div>
)
}
export default ProductMoreDetails;
ProductContext.js
import { createContext } from "react";
import { useReducer } from "react";
export const ProductsContext = createContext();
export const productsReducer = (state, action) => {
switch (action.type) {
// set products
case "SET_PRODUCTS":
return {
...state,
products: action.payload,
}
//set a single product
case "SET_PRODUCT":
return {
...state,
products: action.payload,
}
case 'CREATE_PRODUCT':
return {
products: [action.payload, ...state.products]
}
case 'DELETE_PRODUCT':
return {
products: state.products.filter((product) => product._id !== action.payload._id)
}
case 'UPDATE_PRODUCT':
return {
products: state.products.map((product) => product._id === action.payload._id ? action.payload : product)
}
default:
return state;
}
}
export const ProductsContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(productsReducer, {
products: null
})
return (
<ProductsContext.Provider value={{...state, dispatch}}>
{ children }
</ProductsContext.Provider>
)
}
i created a form in nextjs13 using Formik, Material UI and Yup, but upon click the submit buttom the form get append to the url as queries and the onSubmit button is never called.
i already have use client at the top of my page, yet the validation and onsubmit is not working
below is my form, i cant realy figure out what am doing wrongly
<Formik
validationSchema={validationSchame}
initialValues={{
username: "",
password: "",
}}
onSubmit={async (values, formikHelpers) => {
console.log(values);
}}
>
{({ errors }) => {
return (
<Form>
<Grid item sx={{ marginBottom: 1 }}>
<Field
sx={{ width: "300px" }}
name="username"
as={StyledRedditTextField}
placeholder="Username"
label="Username"
size="medium"
/>
</Grid>
<Grid item>
<Field
sx={{ width: "300px", marginBottom: 2 }}
name="password"
as={StyledRedditTextField}
placeholder="Password"
label="Password"
size="medium"
type="password"
/>
</Grid>
<Grid item>
<Button
type="submit"
variant="contained"
color="primary"
sx={{ width: "300px" }}
size="large"
>
Sign In
</Button>
</Grid>
</Form>
);
}}
</Formik>
<Slider {...settings}>
{this.state.featuredMovies.map(movie =>
<div className="" key={movie._id}>
<Card inverse style={{padding: "10px", width: "90%"}}>
<CardImg src={`/files/${movie.thumbnail}`} alt="Card image cap" />
<CardImgOverlay className="movie-list-overlay">
<CardTitle>{movie.MovieName}</CardTitle>
<CardText>{movie.Description}</CardText>
<CardText>
<small>
<a href="watch">
<Button className="btn-fill btn-movie " color="primary" onClick={movie}>
Watch
</Button></a></small>
</CardText>
</CardImgOverlay>
</Card>
</div>
)}
</Slider>
<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>
i want to pass the movie props on button click to the watch component so the watch component
class WatchMovies extends React.Component {
ComponentDidMount(){
const { player } = this.refs.player.getState();
}
handleDelete = e => {
console.log(this.refs.player.play())
}
handleD = e => {
const {player} = this.refs.player.getState()
console.log(player.currentTime)
console.log(this)
}
render() {
return (
<>
<div className="container-fluid bg-black">
<div className="col-md-12 mx-auto pt-5">
<Row className="" >
<div className="col-md-12 mx-auto py-5">
<Player
ref="player"
width="80%"
playsInline
poster="/assets/bg5.jpg"
src="https://media.w3.org/2010/05/sintel/trailer_hd.mp4"
position="center"
LoadingSpinner
onEnded={() => console.log("ended")}
/>
<Button onClick={this.handleDelete}>D </Button>
<Button onClick={this.handleD}>D </Button>
</div>
</Row>
<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>
i want to pass the movie props on button click to the watch component so the watch component. Watch component is where you will be redirect to watch the movie you selected from the movielist component above
Your onClick needs to be a function
<Button onClick={() => this.doSomething(movie)} />
Then you can access the movie value in that function
const doSomething = (movie) => {
//Do some stuff with the movie
}