I'm trying to add pre-loader icon before rendering an image in React component using the below code:
export default class MediaPostItem extends BaseComponent {
public constructor(props: IMediaPostItemProperties) {
super(props);
this.state = {
imageIsReady: false,
};
}
componentDidMount(): void {
const img = new Image();
img.onload = () => this.setState({ imageIsReady: true });
img.src = this.props.item.featuredImage?.node.sourceUrl;
}
public render(): ReactNode {
const { item } = this.props;
const { imageIsReady } = this.state;
return(
{imageIsReady ? (
<img src={item.featuredImage?.node.sourceUrl}/>
) : (<div> Loading</div>)
})
}
}
Now in the other component I give a HTML strings as a real HTML in a react component using the below code:
<div dangerouslySetInnerHTML={{ __html: props.content }}></div>
The content is including some <img> tags and what I need is to add a pre-loader for these img tags too.
I'm not sure if it's possible or not. Is there any way to apply changes to the HTML strings when it comes from props?
You can do that with ReactDOM.render.
import { render } from "react-dom";
const htmlString = `
<div>
<div id="toBeReplaced"/></div>
</div>
`;
class ReplacedComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
return <h1>Replaced Component</h1>;
}
}
export default class Parent extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
render(
<React.StrictMode>
<ReplacedComponent />
</React.StrictMode>,
document.getElementById("toBeReplaced")
);
}
render() {
return <div dangerouslySetInnerHTML={{ __html: htmlString }}></div>;
}
}
You would need to select the <img> tags, with some attribute (class/id) then loop over them and render your component.