React MUI, How to append to a Masonry Image List - javascript

I'm trying to use the React MUI Masonry Image List component with the infintie scroll component. They seem to work pretty great together.
However, the issue I'm having is appending to the Masonry image list. I successfully append new images, but the whole masonry moves jump and becomes jittery when new images are loaded.
I wonder if it's possible just to add the images to the bottom of the page without the whole thing spazzing out.
Here is a code the illustrates this, basically I just modified the Masonry image list demo:
import * as React from 'react';
import Box from '#mui/material/Box';
import ImageList from '#mui/material/ImageList';
import ImageListItem from '#mui/material/ImageListItem';
import InfiniteScroll from "react-infinite-scroll-component";
import { useEffect, useState } from "react";
export default function MasonryImageList() {
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
const [items, setItems] = useState([]);
const fetchMore = async (itemData) =>{
await sleep(2000)
setItems(prev_items => [...prev_items,...itemData])
}
useEffect(() => {
fetchMore(itemData);
}, []);
return (
<Box id="scrolableDiv" sx={{ width: 800, height: 800, overflowY: 'scroll' }}>
<ImageList variant="masonry" cols={3} gap={8}>
<InfiniteScroll
dataLength={items.length}
next={fetchMore(itemData)}
hasMore={true}
loader={<h4>Loading...</h4>}
scrollableTarget= "scrolableDiv"
>
{items.map((item) => (
<ImageListItem key={item.img}>
<img
src={`${item.img}?w=248&fit=crop&auto=format`}
srcSet={`${item.img}?w=248&fit=crop&auto=format&dpr=2 2x`}
alt={item.title}
loading="lazy"
/>
</ImageListItem>
))}
</InfiniteScroll>
</ImageList>
</Box>
);
}
const itemData = [
{
img: 'https://images.unsplash.com/photo-1549388604-817d15aa0110',
title: 'Bed',
},
{
img: 'https://images.unsplash.com/photo-1525097487452-6278ff080c31',
title: 'Books',
},
{
img: 'https://images.unsplash.com/photo-1523413651479-597eb2da0ad6',
title: 'Sink',
},
{
img: 'https://images.unsplash.com/photo-1563298723-dcfebaa392e3',
title: 'Kitchen',
},
{
img: 'https://images.unsplash.com/photo-1588436706487-9d55d73a39e3',
title: 'Blinds',
},
{
img: 'https://images.unsplash.com/photo-1574180045827-681f8a1a9622',
title: 'Chairs',
},
{
img: 'https://images.unsplash.com/photo-1530731141654-5993c3016c77',
title: 'Laptop',
},
{
img: 'https://images.unsplash.com/photo-1481277542470-605612bd2d61',
title: 'Doors',
},
{
img: 'https://images.unsplash.com/photo-1517487881594-2787fef5ebf7',
title: 'Coffee',
},
{
img: 'https://images.unsplash.com/photo-1516455207990-7a41ce80f7ee',
title: 'Storage',
},
{
img: 'https://images.unsplash.com/photo-1597262975002-c5c3b14bbd62',
title: 'Candle',
},
{
img: 'https://images.unsplash.com/photo-1519710164239-da123dc03ef4',
title: 'Coffee table',
},
];
If you see any glaring errors, please point them out, I've just started with React.

I've faced this similar problem. What worked for me was to supply <img> with a minimum height value.
ie.
<img
src={`${item.img}?w=248&fit=crop&auto=format`}
srcSet={`${item.img}?w=248&fit=crop&auto=format&dpr=2 2x`}
alt={item.title}
loading="lazy"
style={{ minHeight: 10 }} //Added minHeight; 10 is just a sample value
/>
Since masonry lists depend on the height of the element, minHeight serves as a placeholder value while the img has not yet loaded.

Related

Warning: <Element /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements

I'm trying to automatically create React Elements from strings corresponding to the react-icons library. But I am getting the following errors in the console:
Warning: <RiHeartPulseFill /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.
Warning: The tag <RiHeartPulseFill> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.
Currently I have a data file that consists of a name and iconName (see below)
const categoriesData = [
{
name: 'Vitals',
iconName: 'RiHeartPulseFill',
},
{
name: 'Body',
iconName: 'RiBodyScanFill',
},
{
name: 'Sleep',
iconName: 'RiHotelBedFill',
},
{
name: 'Metabolism',
iconName: 'RiLungsFill',
},
{
name: 'Stress',
iconName: 'RiMentalHealthFill',
},
{
name: 'Strength & Training',
iconName: 'RiRunFill',
},
{
name: 'Lifestyle',
iconName: 'RiCellphoneFill',
},
]
export default categoriesData
I want to dynamically render React elements with the exact name as the iconName in the above datafile as React-icons require specific elements with those names.
Then I try to create a list of navigation links (using the React Router <Link> syntax and adding a React-icon + Name. See the code below:
const menuCategories = categoriesData.map((category) => {
const IconElement = category.iconName
return (
<Link
to={`/data/${category.name.toLowerCase()}`}
key={category.name}
className="flex flex-row items-center gap-2"
>
<IconElement />
{category.name}
</Link>
)
})
The issue I run into is the following error: Warning: <RiHeartPulseFill /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.
I does not seems to be incorrect as it actually IS PascalCase. However when I check dev tools I see the following: <riheartpulsefill></riheartpulsefill>
I have no Idea why this happens. Any solutions?
Extra: Does anyone know how I can also import those icon names based on the initial data files. I'm thinking about creating an icon selection tool, so only the selected icons should be imported from the react-icons lib.
If you want to dynamically render these icon components then you'll typically need to import and specify them in the config instead of strings corresponding to their names.
Example:
import {
RiHeartPulseFill,
RiBodyScanFill,
RiHotelBedFill,
RiLungsFill,
RiMentalHealthFill,
RiRunFill,
RiCellphoneFill,
} from "react-icons/ri";
const categoriesData = [
{
name: 'Vitals',
iconName: RiHeartPulseFill,
},
{
name: 'Body',
iconName: RiBodyScanFill,
},
{
name: 'Sleep',
iconName: RiHotelBedFill,
},
{
name: 'Metabolism',
iconName: RiLungsFill,
},
{
name: 'Stress',
iconName: RiMentalHealthFill,
},
{
name: 'Strength & Training',
iconName: RiRunFill,
},
{
name: 'Lifestyle',
iconName: RiCellphoneFill,
},
];
export default categoriesData;
const menuCategories = categoriesData.map((category) => {
const IconElement = category.iconName;
return (
<Link
to={`/data/${category.name.toLowerCase()}`}
key={category.name}
className="flex flex-row items-center gap-2"
>
<IconElement />
{category.name}
</Link>
);
});
An alternative is to create and export a lookup object for the icon components.
import {
RiHeartPulseFill,
RiBodyScanFill,
RiHotelBedFill,
RiLungsFill,
RiMentalHealthFill,
RiRunFill,
RiCellphoneFill,
} from "react-icons/ri";
export const iconMap = {
RiHeartPulseFill,
RiBodyScanFill,
RiHotelBedFill,
RiLungsFill,
RiMentalHealthFill,
RiRunFill,
RiCellphoneFill,
};
const categoriesData = [
{
name: 'Vitals',
iconName: 'RiHeartPulseFill',
},
{
name: 'Body',
iconName: 'RiBodyScanFill',
},
{
name: 'Sleep',
iconName: 'RiHotelBedFill',
},
{
name: 'Metabolism',
iconName: 'RiLungsFill',
},
{
name: 'Stress',
iconName: 'RiMentalHealthFill',
},
{
name: 'Strength & Training',
iconName: 'RiRunFill',
},
{
name: 'Lifestyle',
iconName: 'RiCellphoneFill',
},
];
export default categoriesData;
const menuCategories = categoriesData.map((category) => {
const IconElement = iconMap[category.iconName];
return (
<Link
to={`/data/${category.name.toLowerCase()}`}
key={category.name}
className="flex flex-row items-center gap-2"
>
<IconElement />
{category.name}
</Link>
);
});
To allow for any react-icons/ri icon then in the UI component import all of react-icons/ri and conditionally render the icon component if it exists.
import { Link } from 'react-router-dom';
import * as ReactRiIcons from "react-icons/ri"; // <-- all RI icons
import * as ReactRxIcons from "react-icons/rx"; // <-- all RX icons
const ReactIcons = { // <-- all merged icons set
...ReactRiIcons,
...ReactRxIcons
};
...
const menuCategories = categoriesData.map((category) => {
const IconElement = ReactIcons[category.iconName];
return (
<Link
to={`/data/${category.name.toLowerCase()}`}
key={category.name}
className="flex flex-row items-center gap-2"
>
{IconElement && <IconElement />} // <-- handle possible undefined icon
{category.name}
</Link>
);
});
...
Use React.createElement. Take a look here to see how: Create react component dynamically
Heres my recursive example:
const demoData = [
{
tagName: 'MyButtonComponent',
children: [
{
tagName: 'MyChildComponent'
}
]
},
{
tagName: 'MyOtherComponent'
},
]
function recursivelyRenderChildren(elements) {
if(elements.length) {
return elements.map((element, index) => {
return React.createElement(elementData.tagName, {
key: element.fieldType+'-'+index,
children: recursivelyRenderChildren(element.children)
});
})
}
}
const arrayOfElements = recursivelyRenderChildren(demoData)

Getting content of currently active Text component wrapped inside popover of antd

I am using antd components for my react app. I have a Text component wrapped inside of Popover component. Now in my case this Popover is applied to one particular column of table, i.e. every row-element in that column has a Popover component rendered for it upon mouse hovering.
title: "Name",
dataIndex: "name",
key: "name-key",
sortType: "string",
sortDirections: ["descend", "ascend"],
sorter: (a, b) => a.name.length - b.name.length,
render: (text, record) => (
<Popover>
<Text onMouseOver={handleOnMouseOverCommitId}> {name} </Text>
</Popover>
)
I want to get hold of the row-element's value, the one contained by the above Text component whenever I hover over it. In this case the value denoted by {name} above.
I tried getting it with e.target.value via onMouseOver event, but it returned undefined.
I think I get the reason behind it, because the event.target returns an html node of type <span>.
With a normal div element e.target.value has worked in the past for me. But doing the same thing with a predefined component like antd's Text seems a bit trickier.
Just to elaborate, the Popover has two buttons and based on which button user clicks, I need to render some other components, something like an overlay component.
But in order to do that I would also need to get hold of the text value which originally triggered the Popover.
Below is the code(most of the things removed for preciseness).
record.name is what I ultimately need to capture.
<Popover
content={
<>
<Space>
<Button onClick={showSomeOverlayPaneForName}>
{"View Details for record.name"}
</Button>
<Button href={"https://abc.xyz.com/" + record.role}>
{"View Role Details"}
</Button>
</Space>
</>
}
trigger={"hover"}
>
<Text style={{"color": blue.primary}} copyable={true} onMouseOver={handleOnMouseOverName}>{record.name}</Text>
</Popover>
The handleOnMouseOverName function(which doesn't work anyway) :
const handleOnMouseOverName = (e) => {
//console.log("e.target.value :--- ", e.target.value);
setCurrentActiveName(e.target.value)
}
And once my currentActiveName variable is set(via useState), I use that value inside my function showSomeOverlayPaneForName
const showSomeOverlayPaneForName = (e) => {
axios
.get(
`some-url`,
{
params: {name: currentActiveName}
}
)
.then((response) => {
setData(response.data);
}).catch(reason => {
//xyz
});
}
You need to pass on the record of the enclosing render function to the handleOnMouseOverName function.
Check the following example
import React from 'react';
import 'antd/dist/antd.css';
import './index.css';
import { Space, Table, Button, Popover } from 'antd';
const App = () => {
const data = [
{
key: '1',
name: 'John Brown',
address: 'New York No. 1 Lake Park',
role: 'admin',
},
{
key: '2',
name: 'Jim Green',
address: 'London No. 1 Lake Park',
role: 'user',
},
{
key: '3',
name: 'Joe Black',
address: 'Sidney No. 1 Lake Park',
role: 'manager',
},
];
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
render: (name, record) => {
const content = (
<>
<Space>
<Button
onClick={() => {
viewDetail(record);
}}
>
{'View Details for ' + record.name}
</Button>
<Button href={'https://abc.xyz.com/' + record.role}>
{'View Role Details'}
</Button>
</Space>
</>
);
return (
<>
<Popover content={content} title="Details">
<div
onMouseOver={() => {
handleOnMouseOverName(record);
}}
>
{name}
</div>
</Popover>
</>
);
},
},
{
title: 'Address',
dataIndex: 'address',
key: 'address',
},
];
const handleOnMouseOverName = (record) => {
console.log(record);
};
const viewDetail = (record) => {
console.log(record);
};
return <Table columns={columns} dataSource={data} />;
};
export default App;
Output:
I hope this helps.
From antd docs: https://ant.design/components/popover/#header
Apparently you're supposed to render the <Popover/> with a content={content}-prop
For example
const content = <div>Content to render under title</div>
const App = () => {
const value = "Text to hover";
return (
<Popover content={content} title="Title">
<Text>{value}</Text>
</Popover>
)
}

React JS: How to add multiple placeholder object inside components

Sorry this question might be duplicated, but none of the existing answers helped me
I'm a beginner in React and js
I want to add multiple objects inside the component
Like:
src={url}
name={text}
subTitle={subtext}
my index.js
const tableColumns = [
{
title: 'Title/Artist',
dataIndex: 'name',
key: 'name',
render: (text) => (
<div className="d-flex align-items-center">
<AvatarStatus
shape="square"
src="https://i.scdn.co/image/ab67616d00001e02bd26ede1ae69327010d49946"
name={text}
subTitle="Dua Lipa"
/>
</div>
),
},
];
return (
<>
<Table
className="no-border-last"
columns={tableColumns}
dataSource={recentReleasesData}
rowKey='id'
pagination={false}
/>
</>
my data.js
export const RecentReleasesData = [
{
id: '#5332',
artwork: 'https://i.scdn.co/image/ab67616d00001e02bd26ede1ae69327010d49946',
name: 'Future Nostalgia',
artist: 'Dua Lipa',
label: 'Warner Records',
barcode: '19029500',
releasedate: '2021-02-11',
tracks: '11',
promolink: 'Smart Link',
status: 'Approved',
},
{
id: '#6438',
artwork: 'https://i.scdn.co/image/ab67616d00001e02caf82abb2338880577e472be',
name: 'Love',
artist: 'Someonw',
label: 'UMG Records',
barcode: '50029500',
releasedate: '2017-08-21',
tracks: '2',
promolink: 'Smart Link',
status: 'Rejected',
},
];
My comp AvatarStatus.js
import React from 'react';
import PropTypes from 'prop-types'
import { Avatar } from 'antd';
const renderAvatar = props => {
return <Avatar {...props} className={`ant-avatar-${props.type}`}>{props.text}
</Avatar>;
}
export const AvatarStatus = props => {
const { name, suffix, subTitle, id, type, src, icon, size, shape, gap, text,
onNameClick } = props
return (
<div className="avatar-status d-flex align-items-center">
{renderAvatar({icon, src, type, size, shape, gap, text })}
<div className="ml-2">
<div>
{
onNameClick ?
<div
onClick={() => onNameClick({name, subTitle, src, id})}
className="avatar-status-name clickable">{name}
</div>
:
<div className="avatar-status-name"><a href="javascript:void(0)">
{name}</a>
</div>
}
<span>{suffix}</span>
</div>
<div className="text-muted avatar-status-subtitle">{subTitle}</div>
</div>
</div>
)
}
AvatarStatus.propTypes = {
name: PropTypes.string,
src: PropTypes.string,
type: PropTypes.string,
onNameClick: PropTypes.func
}
export default AvatarStatus;
https://reactjs.org/docs/components-and-props.html
components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “function components” because they are literally JavaScript functions.
codepen example
I found the solution
index.js
render: (_, record) => (
<Flex>
<AvatarStatus
shape="square"
size={50}
src={record.artwork}
name={record.title}
subTitle={record.artist}/>
</Flex>
),

React: mapping through a list of svg images

I am trying to map through a list of svg images and show enough description corresponding to the svg image.
index.js
import {ReactComponent as Pic1} from "../../../../assets/buyer-1.svg";
import {ReactComponent as Pic2} from "../../../../assets/buyer-2.svg";
import {ReactComponent as Pic3} from "../../../../assets/buyer-3.svg";
const data = [
{
id: `1`,
title: "Coming soon",
description:'',
img: Pic1,
},
{
id: `2`,
title: "Coming soon",
description:'',
img: Pic2,
},
{
id: `3`,
tile: "Coming soon",
description:'',
img: Pic3,
},
]
function Test() {
return (
{data.map(({ id, title,description, img }) => (
<div key={id} className="guest--item swiper-slide">
<div>
<img key={id} src={img} alt='mySvgImage' />
<h1>{title}</h1>
<h2>{description}</h2>
</div>
</div>
))}
)}
currently when i check my react website i can only see mySvgImage which is the alt 3 times and cant see the actual image
You are importing SVG's as React Component hence you should use them as Component itself.
In you code you are passing a React Component (SVG's which you imported as React Component) as a src attribute to an <img> tag which is invalid.
import React from "react";
import ReactDOM from "react-dom";
import {ReactComponent as Pic1} from "../../../../assets/buyer-1.svg";
import {ReactComponent as Pic2} from "../../../../assets/buyer-2.svg";
import {ReactComponent as Pic3} from "../../../../assets/buyer-3.svg";
const data = [
{
id: `1`,
title: "Coming soon",
description: "",
Image: Pic1
},
{
id: `2`,
title: "Coming soon",
description: "",
Image: Pic2
},
{
id: `3`,
tile: "Coming soon",
description: "",
Image: Pic3
}
];
function Test() {
return (
<>
{data.map(({ id, title, description, Image }) => (
<div key={id}>
<div>
<Image /> {/* Use Image as Component */}
<h1>{title}</h1>
<h2>{description}</h2>
</div>
</div>
))}
</>
);
}
Because you are importing your images the wrong way. I have made this working CodeSandbox which is exactly the same as your example. Check how I imported images and it's working just fine. CodeSandbox
Where you got it wrong is importing SVG as React Component and using for a src attribute in an img tag.
So u don't need to import as ReactComponent.
You can import this way.
import Pic1 from "../../../../assets/buyer-1.svg";
import Pic1 from "../../../../assets/buyer-1.svg";
import Pic2 from "../../../../assets/buyer-2.svg";
import Pic3 from "../../../../assets/buyer-3.svg";
const data = [
{
id: `1`,
title: "Coming soon",
description:'',
img: Pic1,
},
{
id: `2`,
title: "Coming soon",
description:'',
img: Pic2,
},
{
id: `3`,
tile: "Coming soon",
description:'',
img: Pic3,
},
]
function Test() {
return (
{data.map(({ id, title,description, img }) => (
<div key={id} className="guest--item swiper-slide">
<div>
<img key={id} src={img} alt='mySvgImage' />
<h1>{title}</h1>
<h2>{description}</h2>
</div>
</div>
))}
)}

react-multi-carousel is not rendering

I'm getting data from the state. Now I want to make a carousel slider using react-multi-carousel
I am trying to implement https://www.npmjs.com/package/react-multi-carousel for a news card component that has data coming from the API. So far my code is as follows, but the carousel does not seem to be implementing?
Child Component
import Carousel from 'react-multi-carousel';
import 'react-multi-carousel/lib/styles.css'
const responsive = {
superLargeDesktop: {
breakpoint: { max: 4000, min: 3000 },
items: 5
},
desktop: {
breakpoint: { max: 3000, min: 1024 },
items: 3
},
tablet: {
breakpoint: { max: 1024, min: 464 },
items: 2
},
mobile: {
breakpoint: { max: 464, min: 0 },
items: 1
}
};
const size = 15;
const Itemlist = props.data.slice(0, size).map((item,id) => {
return(
<div className="item px-2 col-md-3" key={item.title}>
<div className="alith_latest_trading_img_position_relative">
<figure className="alith_post_thumb">
<Link
to={{
pathname : `/details/${id}`,
}}
>
<img
alt=""
src={item.multimedia ? item.multimedia[0].url : image}
className="w-100 thumbnail"
/>
</Link>
</figure>
<div className="alith_post_title_small">
<Link
to={{
pathname : `/details/${id}`,
}}
><strong>{item.title.length > 30 ? item.title.substring(0,30) + ".." : item.title}</strong>
</Link>
<p className="meta">
<span>{`${moment(item.published_date).fromNow()}`}</span>
</p>
</div>
</div>
</div>
)
})
return (
<React.Fragment>
<Carousel responsive={responsive}>
{Itemlist}
</Carousel>
</React.Fragment>
);
};
Parent Component
state = {
items : []
}
fetchLatestNews = () => {
api.getRealFeed()
.then(response=>{
this.setState({
items : response.data.results
});
})
}
componentDidMount = () => {
this.fetchLatestNews();
}
render(){
return(
<React.Fragment>
<Item data={this.state.items}/>
</React.Fragment>
)}};
I had the same issue,
Take a look at the specific props. You can add a class to the container, slide or item for adding your css rules. In my case, I had to define a width to the containerClass.
<Carousel
containerClass="carousel-container"
itemClass="carousel-item"
>
... // Your carousel here
And in your css file:
.carousel-container {
width: 100%;
...
}
I'm not sure if this will help, but I had an issue where the carousel becomes empty when I set the prop infinity to true.
Turns out it was because the website I'm working on uses bootstrap rtl.
To fix the issue I just changed the direction of the carousel container to be ltr.
Something like this:
[dir="rtl"] .carousel-container{
direction: ltr;
}
i fix it by adding width properties to the container class
if you using tailwind u need to can set the containerClass width
<Carousel
containerClass={`w-full`}
>
{item}
</Carousel>
I believe you should add import 'react-multi-carousel/lib/styles.css' to your top-level file NOT in the child component file. E.g: _app.tsx for NextJS. It took me about 30m to find out that.
This worked fine for me in functional component: I'm late but it can be usefull to anyone in future.
https://www.npmjs.com/package/react-multi-carousel
import React, { useState } from 'react';
import Carousel from "react-multi-carousel";
import "react-multi-carousel/lib/styles.css";
const SampleCode = props => {
const [maindata, setMaindata] = useState([{'name':"one"},
{'name':"two"}]);
const responsive = {
desktop: {
breakpoint: { max: 3000, min: 1024 },
items: 3,
slidesToSlide: 3 // optional, default to 1.
},
tablet: {
breakpoint: { max: 1024, min: 464 },
items: 2,
slidesToSlide: 2 // optional, default to 1.
},
mobile: {
breakpoint: { max: 464, min: 0 },
items: 1,
slidesToSlide: 1 // optional, default to 1.
}
};
return (
<div>
<Carousel
swipeable={false}
draggable={false}
showDots={true}
responsive={responsive}
ssr={false} // means to render carousel on server-side.
infinite={true}
autoPlay={false}
autoPlaySpeed={1000}
keyBoardControl={true}
customTransition="all .5"
transitionDuration={500}
containerClass="carousel-container"
// removeArrowOnDeviceType={["tablet", "mobile"]}
//deviceType={true}//{this.props.deviceType}
dotListClass="custom-dot-list-style"
itemClass="carousel-item-padding-40-px"
className='location-jobs '
>
{
maindata.map((each) => {
return (
<div className='item p-3 mx-3 d-flex'>
{each.name}
</div>
)
})
}
</Carousel>
</div>
);
}
export default SampleCode;
It is having width issues like I was too using in my project, I have to set the width by using media queries. I don't know why the developer hasn't fixed the issue, but you can try giving a default width in inspect section and then setting up the width by using media queries.

Categories

Resources