PythonSOS
PythonSOS

Reputation: 359

Converting base64 string back to image in React

I'm trying to convert an image that has been changed into base64 on the backend service of my app back to an image on the frontend but seem to be running into a wall in terms of doing so. This is what I have for my code:

PhotoContainer.jsx

class PhotoContainer extends React.Component {

    constructor(props, context) {
      super(props, context);
      this.state = { photo: null };
    }

    async getUserPhoto(accessToken) {
      try {
        const photoResp= await requestAWSGet('path/to/api', undefined, accessToken);
        CachingService.setData('photo', photoResp);
        this.setState({ photo: photoResp});
      } catch (err) {
        log.error('AWSPost /api error:', err);
        throw err;
      }
    }

    render() {
      return (
          <PhotoComponent photo={this.state.photo} />
      );
    }
}

export default PhotoContainer

PhotoComponent.jsx

const PhotoComponent = props => (
    <>
        {`data:image/png;base64,${props.photo}`} alt={'photo'}
    </>
);

export default PhotoComponent;

An example of a component where I would call the PhotoContainer,jsx

class ExampleComponent extends React.Component {
  render() {
    return (
         <Container>
                <Card>
                    <Card.Img src={<PhotoContainer />} alt={'photo'} />
                    <Card.Body>
                         <p>Some text</p>
                    </Card.Body>
                </Card>
            </Container>
    );
  }
}

export default ExampleComponent;

Am I somehow using the conversion line wrong in the component or is there a deeper issue with the way I'm setting up my container?

Upvotes: 0

Views: 1858

Answers (1)

Yalung Tang
Yalung Tang

Reputation: 639

You need to refactor PhotoComponent this way

const PhotoComponent = props => (
    props.photo ? <Card.Img
      src={`data:image/png;base64,${props.photo}`}
      alt={'photo'}
    /> : ''
);

export default PhotoComponent;

The ExampleComponent would need to just instance PhotoContainer

class ExampleComponent extends React.Component {
  render() {
    return (
         <Container>
                <Card>
                    <PhotoContainer />
                    <Card.Body>
                         <p>Some text</p>
                    </Card.Body>
                </Card>
            </Container>
    );
  }
}

export default ExampleComponent;

You can leave PhotoContainer as is.

Hope this helps.

Upvotes: 2

Related Questions