React + Splide.js Grid Extension functionality - javascript

So I can't find anywhere an example for Splide Grid Extension integration in React. How exactly does this work? What am I missing?
import React, { useEffect, useState } from "react";
import { Splide, SplideSlide } from '#splidejs/react-splide';
import { Grid } from "#splidejs/splide-extension-grid";
import Container from "../layout/Container";
import Section from "../layout/Section";
import classes from './Jobs.module.css';
const Jobs = ({blok}) => {
const [jobs, setJobs] = useState([]);
...
return <Section>
<Container>
<div className={classes.slider_wrapper}>
<Splide aria-label="jobs slider" options={ {
pagination: false,
arrows: false,
grid: {
rows: 2,
cols: 2,
},
} } extensions={{ Grid }}>
{jobs && jobs.map(item => (
<SplideSlide key={item.uuid} >
<div className={classes.item}>
<div className={classes.content}>
<div className={classes.title}>{item.content.title}<span>.</span></div>
</div>
</div>
</SplideSlide>
))}
</Splide>
</div>
</Container>
</Section>
}
export default Jobs;
This only returns a normal Splide slider without a grid. How exactly can i get a grid of 2x2 for example?

Related

useSWR to pass dynamic 'Cards' in to a dynamic index on slides in Swiperjs

I am currently experiencing issues when trying to pass data from my Slider (SwiperJS as parent component) in to my dynamic Card component as a child.
I am using SWR to data fetch from an api endpoint (dummy data) in order to test functionality.
Here is my code...
./components/Slider.js - Parent component
import React, { useState } from 'react'
import { Swiper, SwiperSlide} from 'swiper/react'
import { Virtual, Navigation, FreeMode } from "swiper"
import { SongCard } from './Songcard'
import useSWR from 'swr'
const fetcher = (url) => fetch(url).then((res) => res.json())
// Import Swiper styles
import 'swiper/css';
import 'swiper/css/virtual'
import 'swiper/css/navigation'
import 'swiper/css/free-mode'
export default function Slider() {
const { data, error } = useSWR('https://api.npoint.io/fdb9617039cbd942c147', fetcher)
if(!data) return <div className={style.loading}>Loading</div>
if(error) return <div>Error</div>
// Create array with dynamic slides
const slides = Array.from({ length: data.length }).map(
(el, index) => `Slide ${index + 1}`)
console.log(data.length)
return (
<Swiper
modules={[Virtual, Navigation, FreeMode]}
slidesPerView={7}
virtual
centeredSlides={true}
initialSlide="3"
navigation={true}
grabCursor={true}
breakpoints={{
280: {
slidesPerView: 1,
},
360: {
slidesPerView: 2,
},
584: {
slidesPerView: 3,
},
768: {
slidesPerView: 4,
},
1024: {
slidesPerView: 5,
},
1260: {
slidesPerView: 6,
},
}}
>
{slides.map((slidecontent, index) => (
<SwiperSlide key={slidecontent} virtualIndex={index}>
{data.map((data) =>{
return <SongCard key={data.songId} />
})}
</SwiperSlide>
))}
</Swiper>
)
}
./components/SongCard.js - Child component
import Image from 'next/image'
import styles from '../styles/Card.module.css'
import Script from 'next/script'
export function SongCard(data) {
return (
<section>
<Script src="https://kit.fontawesome.com/4dcae86ee9.js" crossorigin="anonymous"/>
<div className={styles.container}>
<div className={styles.songImg}>
<div className={styles.imgWrapper}>
<Image
className={styles.songImage}
priority="true"
src="/counting.png"
alt={data.songName}
width="200px"
height="200px"
layout="intrinsic"
objectPosition="center"
/>
</div>
<div className={styles.songImage}>
<span><i className="fa-solid fa-fire-flame-curved fa-beat"></i></span>
</div>
<div className={styles.songInfo}>
<p className={styles.songTitle}></p>
<p className={styles.artistTitle}>{data.screenName}</p>
<p className={styles.vibes}>{data.songVibeTags}</p>
<p className={styles.genres}>{data.songGenreTags}</p>
</div>
<div className={styles.iconContainer}>
<span className={styles.likes}>
<i className="fa-solid fa-thumbs-up"></i>
<p className={styles.countLikes}>{data.songLikes}</p>
<i className="fa-solid fa-play"></i>
<p className={styles.countPlays}>{data.songPlays}</p>
</span>
<span className={styles.actions}>
<i className="fa-regular fa-bookmark"></i>
<i className="fa-solid fa-share-nodes"></i>
</span>
</div>
</div>
</div>
</section>
)
}
There seems to be two issues that I have here. The first is that the data is not passing in to the 'Child component'.
The second issue seems more troubling and that is that the number of slides seems to be greater than the number of objects that are in the data api endpoint.
It should be a Dynamic number of slides matching data.length.
As far as I can tell, I am only pulling back the initial data once to populate the slides.
This is causing all of the slides to scrunch up to try and occupy the same amount of space that the data length would normally have used.
Any and all advice would be much appreciated after Doc surfing for a few days now.
It is possible that I am trying to tackle the problem the wrong way...if so please guide me so I can refactor.
Thanks and have a great day.
First of all you forgot to pass the data to the SongCard component, do it like that:
// Add data prop here
<SongCard key={data.songId} data={data} />
// And don't forget to destructure it in the component:
export function SongCard({ data }) {
// ...
}
And second, do you even need this slides array? Just iterate over your data directly:
{data.map((song) => (
<SwiperSlide key={song.songId}>
<SongCard data={song} />
</SwiperSlide>
))}
I've made quick minimal reproduction on Codesandbox if you want to check working example:

Handle multiple checkbox components in React

I´m having issues with creating my checkbox component(s).
Since I´m mapping over an object´s entries, where the keys are the sectiontitles and the values are arrays, filled with the checkable features.
I´m also using tailwind. I will let the code speek for itself I think :D
Checkboxes
Object structure, which im passing as a prop, down to the checkboxes component:
const features = {
Features: [
'Mintable',
'Burnable',
'Pausable',
'Permit',
'Votes',
'Flash Minting',
'Snapchots'
],
'Access Control': ['Ownable', 'Roles'],
Upgradeability: ['Transparent', 'UUPS']
};
Checkboxes component, which renders the checkbox component multiple times by mapping over the object (Ik the id is missing, but I dont know how to control the ID´s:
import React from 'react';
import { connect, useDispatch } from 'react-redux';
import Checkbox from '../../layout-blueprints/Checkbox';
import { featureCheckboxClick } from './Redux/actions';
const FeaturesComponent = ({ features }) => {
const dispatch = useDispatch();
return (
/* Card layout and heading */
<div className="bg-white p-4 rounded col-span-2 row-span-5">
{Object.entries(features).map(([key, value]) => {
return (
<div key={key}>
<h5 className="text-black m-t-4">{key}</h5>
<div className="border-bottom border-primary pb-2 mb-4 mr-20">
{/* Render feature checkboxes */}
{value.map((feature) => {
return (
<div className="flex justify-between m-2" key={feature}>
<div>
<Checkbox
onChange={() => dispatch(featureCheckboxClick(feature))}
/>
<span className="pl-2 text-lg">{feature}</span>
</div>
</div>
);
})}
</div>
</div>
);
})}
</div>
);
};
export default connect()(FeaturesComponent);
checkbox-component:
import React from 'react';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import { faCheck } from '#fortawesome/free-solid-svg-icons';
const Checkbox = () => {
return (
<label htmlFor="check-box-1" className="cursor-pointer relative">
<input
type="checkbox"
className="check-box-1 appearance-none h-4.5 w-4.5 border-2 border-primary rounded-sm relative translate-y-0.5"
/>
<FontAwesomeIcon
icon={faCheck}
className="-translate-x-4 translate-y-0.5 h-4.5 w-4.5 text-sm absolute text-white text-opacity-0 transition check-1 duration-200"
/>
</label>
);
};
export default Checkbox;
css tailwind directives (should be readable, even if you never worked with tailwind):
#tailwind components;
#tailwind utilities;
.check-box-1:checked {
#apply bg-primary;
}
.check-box-1:checked ~ .check-1 {
#apply text-opacity-100;
}
That´s all the code. Like I said, I´d usually work with a useState array or so, but It´s kinda hard to control it, bc there is so much nesting in the mapping, or am I thinking too complicated?
I´m honestly clueless and am glad for any help I can get, cheers!
I hope this helps
import { NextPage } from "next"
import { useState } from "react"
import CheckboxList from "../../../components/learn22/CheckboxList"
const myFoodList = [
'김치',
'고구마',
'감자',
'피자',
'햄버거',
'라면',
'제육볶음',
'삼계탕',
'닭곰탕',
'추어탕'
]
const MyCheckList: NextPage = () => {
const [checkedFoods, setCheckedFoods] = useState<string[]>([])
const onMyFoodChecked = (checked : string[]) => {
setCheckedFoods(checked)
console.log(checked)
}
return(
<CheckboxList
checkedFoods ={checkedFoods}
onCheck = {onMyFoodChecked}
foods = {myFoodList}
/>
)
}
export default MyCheckList;
import { FunctionComponent } from "react";
interface Props {
checkedFoods ?: string[];
onCheck: (checked : string[]) => void;
foods ?: string[];
}
const CheckBoxList : FunctionComponent<Props> = ({
checkedFoods =[],
onCheck,
foods =[]
}) => {
return (<ol>{foods.map((food, idx)=>
<li key={food + '-' + idx}>
<input type='checkbox' checked={checkedFoods?.includes(food)}onChange={(e)=>{
if(e.target.checked){
onCheck([...checkedFoods!, food])
} else{
onCheck(checkedFoods.filter((_food)=> _food !== food));
}
}}/>
<span>{food}</span>
</li>
)}
</ol> );
}
export default CheckBoxList;
[blog post that shows how to Handle multiple checkbox components in React][1]
[1]: https://codemasterkimc.tistory.com/459

React - JSON file won't render

I am building out a row of react-icons. When selected the icons to display content from a static .JSON file. I am trying to combine the following events:
Change color when clicked
Change/Switch between the static .JSON content when clicked.
I tried to combine the 2 actions inline based on this post.
However, only the color changes, not the .JSON data.
Thank you in advance, any help or guidance would be appreciated.
Here is my code below:
import React, { useState } from "react";
import "../Styles/arrow.css";
import { BsFillPeopleFill } from "react-icons/bs";
import { GiLinkedRings } from "react-icons/gi";
import { GoArrowRight } from "react-icons/go";
function Icon(props) {
const handleClick = (messageKey) => () => props.setSelectedIcon(messageKey);
const [bg, changeBGColor] = React.useState(1);
return (
<div className="icon-arrow">
<div className="arrow">
<div className="arrow-line" />
<div className="arrow-icon">
<GoArrowRight />
</div>
</div>
<div className="icons">
<GiLinkedRings
className="rings"
onClick={() => {
handleClick("rings");
changeBGColor(1);
}}
style={{
backgroundColor: bg === 1 ? "#e3e1dc" : "#ae7a67",
}}
/>
<BsFillPeopleFill
className="family"
onClick={() => {
handleClick("family");
changeBGColor(2);
}}
style={{
backgroundColor: bg === 2 ? "#e3e1dc" : "#ae7a67",
}}
/>
</div>
</div>
);
}
export default Icon;
My .JSON Data: iconmessage.json
{
"rings": {
"image": "rings.jpg",
"title" : "Rings",
"message":"Lorem Ipsum"
},
"family": {
"image": "family.jpg",
"title" : "Family is essential",
"message":"Lorem Ipsum"
}
}
Icons/.JSON being pulled from IconMessage.JSX
import React from "react";
import "../Styles/iconmessage.css";
import messages from "../Static/iconmessage.json";
function IconMessage(props) {
const message = messages[props.selectedIcon]
return (
<div className="icon-message">
<div className="title-message">
<div className="title">{message.title}</div>
<div className="message">{message.message}</div>
</div>
<div className="image">
<img src={`/images/${message.image}`} alt="" srcset="" />
</div>
</div>
)
}
export default IconMessage
What you did what correct from the onClick perspective. I'd say that the problem is the value you pass. Are you sure that when you pass "rings" to selectedIcon, it should render the JSON as you'd wish?
I think the problem is that you access messages.title, messages.message, instead of messages.image.title, messages.image.message.

Random ID being passed in whenever going to a unique route with Link tag

I am in the process of making a recipe app and currently, I am building a component that displays a number of recipes (depending on how much I determine via API call) within a carousel slideshow which showcases the image of recipe, title, and other info. I tried using a Link tag for a recipe to go to its own unique route (/recipe/:id) but every time it goes to that route, it never passes in the current recipe's ID that's being displayed currently in the carousel. Thank you. Edit: upon closer examination, it seems like it's only getting the ID of the last recipe object within the recipes array of objects. Any help or ideas?
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';
import Slider from 'react-slick';
import { faClock, faUser, faGlobe, faUtensils } from '#fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import { Route, NavLink, Link } from 'react-router-dom';
import RecipeInfo from '../RecipeInfo';
const Slideshow = () => {
const settings = {
dots: true,
fade: true,
infinite: true,
slidesToShow: 1,
arrows: true,
slidesToScroll: 1,
className: 'slides',
autoplay: true,
speed: 2000,
autoplaySpeed: 3300,
centerPadding: '60px'
};
const [ recipes, setRecipes ] = useState([]);
const diets = [ 'Asian', 'Greek', 'American', 'Chinese' ];
const diet = diets[Math.floor(Math.random() * diets.length)];
useEffect(() => {
axios
.get(
'https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/search?number=20&offset=0&type=main%20course',
{
headers: {
'x-rapidapi-host': 'spoonacular-recipe-food-nutrition-v1.p.rapidapi.com',
'x-rapidapi-key': 'e7bb7cb790mshb2eb009f0d98772p1ec6e5jsnc524d12e4092'
},
params: {
diet: `${diet}`
}
}
)
.then((res) => {
setRecipes(res.data.results);
console.log(res.data.results);
})
.catch((err) => {
console.log(err);
});
}, []);
return (
<div>
<Slider {...settings}>
{recipes ? (
recipes.map((recipe) => {
return (
<div key={recipe.id}>
<div className="slides-container">
<img
className="recipe-image"
width="35%"
alt={recipe.title}
src={`https://spoonacular.com/recipeImages/${recipe.id}-636x393.jpg`}
/>
<div className="card-info">
{' '}
<Link to={`/recipe/${recipe.id}`} key={recipe.id}>
<h1>
{' '}
<FontAwesomeIcon icon={faUtensils} /> {recipe.title}
</h1>
</Link>
<p>Recipe Id: {recipe.id}</p>
<br />
<h3>
<FontAwesomeIcon icon={faClock} /> Ready In: {recipe.readyInMinutes} Minutes
</h3>
<br />
<h4>
<FontAwesomeIcon icon={faUser} /> Servings: {recipe.servings}
</h4>
<br />
<br />
<a href={recipe.sourceUrl} target="_blank" rel="noopener noreferrer">
<h5>
<FontAwesomeIcon icon={faGlobe} /> Recipe Link
</h5>
{/* {recipe.sourceUrl} */}
</a>
</div>
</div>
</div>
);
})
) : (
<p>Loading Recipes</p>
)}
</Slider>
</div>
);
};
export default Slideshow;

Get keys of every object and insert that data into array

I want to get the keys of every frame object and insert that data into array. After it should have arrays in array. I have tried multiple ways and have not figured it out. Any suggestions?
This is the output.json that i will be working with, it could go up to 550 frame number's.
[{"frame_number": 1, "roi0": [101.78202823559488, 99.39509279584912, 49.546951219239915, 29.728170731543948], "intensity0": 80.0, "roi1": [101.78202823559488, 99.39509279584912, 49.546951219239915, 29.728170731543948], "intensity1": 157.0},
{"frame_number": 2, "roi0": [102.56623228630755, 97.95906005049548, 50.25603182631066, 30.153619095786393], "intensity0": 80.0, "roi1": [102.56623228630755, 97.95906005049548, 50.25603182631066, 30.153619095786393], "intensity1": 158.0},
{"frame_number": 3, "roi0": [103.39336535376313, 98.20468223716023, 49.58465295946593, 29.750791775679556], "intensity0": 80.0, "roi1": [103.39336535376313, 98.20468223716023, 49.58465295946593, 29.750791775679556], "intensity1": 157.0},
The following is my app.js where i get the output.json file from the api and send it through to a component, button_footer
import "bootstrap/dist/css/bootstrap.css";
import React from "react";
import Radio_Button from "./components/Radio_Button.js";
import Buttons_Footer from "./components/Buttons_Footer.js";
import LeftPane from "./components/LeftPane.js";
//import './App.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { apiResponse: [] };
}
// Comunicate with API
callAPI() {
fetch("http://localhost:9000/IntensityAPI") //React app talks to API at this url
.then(res => res.json())
.then(res => this.setState({ apiResponse: res }));
}
componentWillMount() {
this.callAPI();
}
render() {
return (
<div className="App">
<header className="App-header">
<p></p>
<div class="row fixed-bottom no-gutters">
<div class="col-3 fixed-top fixed-bottom">
<LeftPane></LeftPane>
</div>
<div class="offset-md-3" >
<Buttons_Footer readings = {this.state.apiResponse}/>
</div>
</div>
</header>
</div>
);
}
}
export default App;
The following is the button_footer which is where I tried to handle this data and put it in a array but failed.
import $ from "jquery";
import React, { Component } from 'react';
import { MDBFormInline } from 'mdbreact';
import { Container, Row, Col } from 'reactstrap';
import Radio_Button from "./Radio_Button.js";
// Footer Component with checkbox's used to select region/region's of interest
class Buttons_Footer extends Component {
// Enables the Functionality of the "Select Multiple Region's" switch using jquerys
componentDidMount() {
$(".region").click(function(e){
if($('#customSwitches').is(':not(:checked)')){
if($('.region:checked').length > 1){ // Multiply regions unable to be selected
alert('You can not check multiple');
e.preventDefault();
}
}
});
$("#customSwitches").click(function(e){ // Multiply regions able to be selected
$(".region").prop('checked', false);
}); }
//<p>{this.props.region.roi0}</p>
render() {
return (
<Container class = "container offset-md-3" >
<div className='custom-control custom-switch' >
<input type='checkbox' className='custom-control-input' id='customSwitches' />
<label className='custom-control-label' htmlFor='customSwitches'>
Select Multiple Region's
</label>
{this.props.readings.map((region)=>{
return <Radio_Button region ={region} key ={region.frame_number}/>
})}
Object.keys({this.props.readings}).map((key, index) => {
const myItem = myObject[key]
return <MyComponent myItem={myItem} key={index} />
})
<MDBFormInline>
<input class="region" type="checkbox" name="region1" value="1" />
<label for="region1"> 1</label>
<input class="region" type="checkbox" name="region2" value="2" />
<label for="region2"> 2</label>
</MDBFormInline>
</div>
</Container>
);
}
}
export default Buttons_Footer;
```
Maybe this work
this.props.readings.map((reading, index) => {
Object.keys(reading).map((key, index) => {
const myItem = reading[key]
return <MyComponent myItem={myItem} key={index} />
})
})

Categories

Resources