score:6
these answers were helpful but there's a way to achieve this without needing to pass a key
each time by taking advantage of the useeffect
hook:
useeffect(() => {
set_imgsrc(src);
}, [src]);
additionally, the onerror
event doesn't seem to trigger for certain images (i believe layout='fill'
doesn't trigger it in certain scenarios), for those cases i've been using the onloadingcomplete
and then i check if the width of the image is 0
onloadingcomplete={(result) => {
if (result.naturalwidth === 0) { // broken image
set_imgsrc(fallbacksrc);
}
}}
full code:
import image from "next/image";
import { useeffect, usestate } from "react";
export default function imagefallback({ src, fallbacksrc, ...rest }) {
const [imgsrc, set_imgsrc] = usestate(src);
useeffect(() => {
set_imgsrc(src);
}, [src]);
return (
<image
{...rest}
src={imgsrc}
onloadingcomplete={(result) => {
if (result.naturalwidth === 0) {
// broken image
set_imgsrc(fallbacksrc);
}
}}
onerror={() => {
set_imgsrc(fallbacksrc);
}}
/>
);
}
score:10
@juliomalves has given 99% percent of the answer, however i would like to add to it. there is a problem when changing the src in his solution, as the image would not update because it's getting the imgsrc value which is not getting updated. this is my addition to his answer:
import react, { usestate } from 'react';
import image from 'next/image';
const imagefallback = (props) => {
const { src, fallbacksrc, ...rest } = props;
const [imgsrc, setimgsrc] = usestate(false);
const [oldsrc, setoldsrc] = usestate(src);
if (oldsrc!==src)
{
setimgsrc(false)
setoldsrc(src)
}
return (
<image
{...rest}
src={imgsrc?fallbacksrc:src}
onerror={() => {
setimgsrc(true);
}}
/>
);
};
export default imagefallback;
now imgsrc is used only as a flag, and there is tracking of src value, which helps to change the image even if you had an image that had the fallback image on before.
score:27
you can create a custom image component that extends the built-in next/image
and adds the fallback logic if the image fails to load by triggering the onerror
callback.
import react, { usestate } from 'react';
import image from 'next/image';
const imagewithfallback = (props) => {
const { src, fallbacksrc, ...rest } = props;
const [imgsrc, setimgsrc] = usestate(src);
return (
<image
{...rest}
src={imgsrc}
onerror={() => {
setimgsrc(fallbacksrc);
}}
/>
);
};
export default imagewithfallback;
then, you can directly use the custom component instead of next/image
as follows:
<imagewithfallback
key={videoid}
layout="fill"
src={`https://i.ytimg.com/vi/${videoid}/maxresdefault.jpg`}
fallbacksrc={`https://i.ytimg.com/vi/${videoid}/hqdefault.jpg`}
/>
passing a key
prop to trigger a re-render on videoid
change.
Source: stackoverflow.com
Related Query
- What is the best way to have a fallback image in NextJS?
- What is the best way to have variable attributes in JSX?
- What is the best way to understand that all redux-forms have been successfully submitted?
- What is the best way to have a React-generated static (SEO) "public" frontend alongside a CRA "private" app?
- What is the best way to access redux store outside a react component?
- What is the best way to redirect a page using React Router?
- What is the best way to trigger onchange event in react js
- What is the best way to deal with a fetch error in react redux?
- What is the best way to add a value to an array in state
- What is the best way to manage a user's session in React?
- React - What is the best way to handle login and authentication?
- what is the best way to mock window.sessionStorage in jest
- What is the best way to create a single MobX store for an app?
- ReactJS : What is the best way to give keys in array element
- What is the best way to test Window Scroll Event Handlers with Enzyme?
- What is the best way to secure Firebase API keys in a react app so it is not accessible publicly?
- What is the best way to get the selected value from a React-Select component?
- What is the best way of defining optional propTypes in react?
- What is the best way to implement undo state change (undo store/history implementation) in React Redux
- What is the best way to create text input Redux
- What is the best way to make multiple get request with axios in a loop?
- What is the best way to use redux action in useEffect?
- What is the best way to export modules with submodules in (Vue, React)
- What is the best and most efficient way to bind callbacks in ReactJS? In the constructor or in the render method or as a property initializer?
- What is the best way to do Error Handling in React Native App.
- What is the best way to update my react state when data in database changes?
- What is the best way to use a different API URL in production for a create-react-app using docker?
- What is the best way to create parameter of the component in React?
- React styled-component / e2e testing: What is the best way to use css selector?
- In React, what is the best way to define action types?
More Query from same tag
- How to test a component that renders children as props in enzyme
- Trouble programmatically changing routes with React Router
- Nested map cannot render <Text> element from main loop
- The confusion the way setState works in this code
- Slider inside of Modal is not working - React + Material UI
- How can I make a file available app wide without importing it?
- replace componentWillRecieiveProps in react 16 in redux?
- Dispatch redux not executed
- react How do I check if string is empty
- React i18next::backendConnector issue whenever I change the namespace
- How to perform multiple queries with Apollo graphql HOC?
- State is being updated but not displaying
- error - unhandledRejection: Error: Not supported at Object.react-markdown
- TypeScript and createContext - Property is missing on type
- unable to add a border to popup modal
- Having trouble writing custom query to update mySql database
- 'useEffect' not run only once
- react reducer initialState didnt show as expexted
- I cannot find the error TypeError: Cannot read properties of undefined (reading 'name')
- Trouble batch setting a document field by docId in Firestore
- Reactjs - Unable to modify Input
- React: Navbar is not changing after token is passed to localstorage
- UseEffect not fired when redux props change caused by async api call with redux-thunk
- Rendering an iFrame within a React Portal
- How can I make this dropdown show all of the fifty states instead of "option #"
- strange behavior when trying to update crud
- How to use the key (defined from lists items key) as prop on my Modal
- Route loading or mounting twice in React Router
- how i get querySelectorAll html elements in react?
- child views are overriding parent view's boundary. [react-native]