2

How would I redirect the image url when error is occuring? Because this is not working. I need a solution for 2021.

edit: Since I am mapping through an array. How would I define password before the return function?

          const dispatch = useDispatch();
          const passwordList = useSelector((state) => state.passwordList);
          const { loading, error, passwords } = passwordList;
        
          const [imgSrc, setImgSrc] = useState(
            "`https://example.com/${password.url}`"
          );
        
          const handleError = () =>
            setImgSrc("https://upload.wikimedia.org/wikipedia/commons/c/ce/Example_image.png");
        
 

       <ul >
{passwords.map((password) => (
  <div>
    <li
      key={password.id}
     >
      <img
        src={imgSrc}
        onError={handleError}
      />
    </li>
  </div>
))}
</ul>
        

Here's an example of what I am trying to do: https://jsfiddle.net/maccman/2kxxgjk8/3/

Toan Lam
  • 109
  • 2
  • 12

1 Answers1

2

Functional component

import { useState } from "react";

const SomeComponent = () => {
  const [imgSrc, setImgSrc] = useState(/* original src */);

  const handleError = () => setImgSrc("https://upload.wikimedia.org/wikipedia/commons/c/ce/Example_image.png");

  return <img src={imgSrc} onError={handleError} />
};

Class component

import { Component } from "react";

class SomeComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { imgSrc: /* original src */};
  }
  
  handleError = () => this.setState({
    imgSrc: "https://upload.wikimedia.org/wikipedia/commons/c/ce/Example_image.png"
  });

  render() {
    return <img src={imgSrc} onError={handleError} />;
  }
}
Matthew Kwong
  • 2,548
  • 2
  • 11
  • 22
  • ok, one small problem. I using a template literal to call and define imgSrc with useState. Is there anyway to define password in order to map outside of the return function? or this is impossible. i have updated the post again. would I have to export and import a separate component? – Toan Lam Nov 19 '21 at 03:43
  • https://stackoverflow.com/questions/34097560/react-js-replace-img-src-onerror just what I was looking for – Toan Lam Nov 19 '21 at 06:01