Vandanaa Swaminathan :
I am new to React. I have a functional component that is used to render am image and some properties of an image passed as props to the component. I would like to update the image source when there is an error rendering the image. I would also like to update the state property of the parent component and pass it back to the parent. I am not sure how to achieve the same. I have been struggling for so long to achieve this. Please can someone help me solve this issue. Many thanks in advance.
import React, { useState } from 'react';
import PropTypes from 'prop-types';
const ImageRenderer = props => {
const [assetInfo, setAssetInfo] = useState(props); //assetInfo contains asseturl, type, name, type of the image, isAssetPublished
return(
<div id="asset-img">
<p> Name: {assetInfo.assetInfo.name} </p>
<p> Type: {assetInfo.assetInfo.type} </p>
<p> Url: {assetInfo.assetInfo.assetUrl} </p>
<img src={assetInfo.assetInfo.assetUrl} alt="name" onError={e => {
setAssetInfo(assetInfo => {
return { ...assetInfo, assetUrl: 'https://example.com/404-placeholder.jpg' } //would like to update the asset url to 404 and also set isAssetPublished to false and pass it back to parent to update parent state
});
}}/>
</div>
)
}
ImageRenderer.propTypes = {
assetInfo:PropTypes.object.isRequired
};
export default ImageRenderer;
ilkerkaran :
Instead of using new state in ImageRenderer
component, you can just pass setState of Parent via props like this;
parent component
import React, { useStae } from 'react'
const parentCompoennt = props => {
const [assetInfo,setAssetInfo] = useState();
return (
<ImageRenderer assetInfo={assetInfo} setAssetInfo={setAssetInfo} />
);
}
imageRenderer component
const ImageRenderer = props => {
return(
<div id="asset-img">
<p> Name: {props.assetInfo.assetInfo.name} </p>
<p> Type: {props.assetInfo.assetInfo.type} </p>
<p> Url: {props.assetInfo.assetInfo.assetUrl} </p>
<img src={props.assetInfo.assetInfo.assetUrl} alt="name" onError={e => {
props.setAssetInfo(assetInfo => {
return { ...props.assetInfo, assetUrl: 'https://example.com/404-placeholder.jpg' } //would like to update the asset url to 404 and also set isAssetPublished to false and pass it back to parent to update parent state
});
}}/>
</div>
)
}
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=405254&siteId=1