Rendering an image with react

Hello there. I am very new to all this and am trying to render a simple image in my React (class based) component.
This is my code:
const Client = Prismic.client(apiEndpoint, { accessToken })

class Home extends Component {

  constructor(props) {

    super(props);

    this.state = {

      setDocData:this.setDocData,

      doc:null,

    }

  }

  componentDidMount() {

    const fetchData = async () => {

      const response = await Client.query(

        Prismic.Predicates.at('document.type', 'home')

      )

      if (response) {

        this.setState({

          doc:response.results

        })

        console.log(typeof(this.state.doc));

      }

    }

    fetchData()

  }

  render() {

    const { content } = this.props;

    // const { doc } = this.state;

    return (

      <div className={styles.host}>

        <h1>IT WORKS</h1>

        <pre>{JSON.stringify(this.state.doc, null, 2)}</pre>

      </div>

    );

    // return <img src={JSON.stringify(this.state.doc.data.our_modules.url)} alt={doc.data.our_modules.alt} />

  }

}

export default Home;

I am already able to render the JSON format of the response (doc) object and the state is updating itself successfully I believe but as soon as I try to render an I get the error: doc is null!!!

Hello Maryam,

Thanks for reaching out to us.

Can you please confirm this: Are you getting issues while rendering an image element render? If yes, can you try alt attribute like this.state.doc.data…. Instead of doc.data.

Please add a check above return block in render function like;
if (this.state.doc) {// add your code of return block here……}
This is to assure you have set the state successfully for the doc variable.

Looking forward to hearing from you.

Thanks,
Priyanka

Hello Priyanka,

  • Edit: the API ID was missing from the img src and alt which is now corrected but the same error persists.

Thanks so much for getting back to me. have done what you told me and this is what I get:

Error I receive:

What are you getting in const response object in the console? Can you print it on the console and give it back to me? (send me a private message if you don't want to share your data publically).

Thank you! Sent you a private message!

Solved in personal chat:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.