hygraph/rich-text

Impossible to render a clickable image with Reactjs and rich-text

severine-cuenot opened this issue · 9 comments

Hey there!
First of all sorry about my English, it's not my first langage :)

What I want

I'm trying to make images automaticaly clickable in my React js app.

The issue :

No matter how I code it, it doesn't work. I tried with a lightroom library, a modal from react-modal-image, nothing works.
My last attempt was with a simple link but it doesn't work either.

My last try

Component code

function PostCard({ posts }) { const unipopiaPosts = posts.filter((post) => post.node.categories.some((category) => category.nom === 'Unipopia'));

return (
<article className="post__block"> {unipopiaPosts.map((unipopia) => ( <div key={unipopia.node.slug}> <div className="post__title"> {unipopia.node.titre} </div> <div className="post__excerpt"> {unipopia.node.extrait} </div> <div className="post__content"> <RichText content={unipopia.node.contenu.raw} renderers={{ image: ({ node }) => { const imageUrl = node.children[0].src; return ( <a href={imageUrl} target="_blank" rel="noopener noreferrer"> <img alt={node.children[0].title} src={imageUrl} height={node.children[0].height} width={node.children[0].width} /> </a> ); }, }} /> </div> </div> ))} </article>
); }

Could you help me please?

Hey! No worries. I never used lightroom, but I helped someone with a different library in the past, and it worked. See #71

Here's an example on how to use it with react-modal-image. I hope it helps!

https://codesandbox.io/s/eager-kirch-2c2m3t?file=/src/App.tsx

#reopen

Hey there! Thanks a lot for your help @jpedroschmitz but it still doesn't work T____T It drives me crazy!
Maybe I have a mistake somewere else in my code? I'm quite new to coding so... here is my code with yours :

// React imports
import { useState } from 'react';
import PropTypes from 'prop-types';
import { RichText } from '@graphcms/rich-text-react-renderer';
import Lightbox from 'react-awesome-lightbox';
import 'react-awesome-lightbox/build/style.css';
import './style.scss';

function PostCard({ posts }) {
  const unipopiaPosts = posts.filter((post) => post.node.categories.some((category) => category.nom === 'Unipopia'));
  const [clickedImage, setClickedImage] = useState('');

  return (
    <article className="post__block">
      {unipopiaPosts.map((unipopia) => (
        <div key={unipopia.node.slug}>
          <div className="post__title">
            {unipopia.node.titre}
          </div>
          <div className="post__excerpt">
            {unipopia.node.extrait}
          </div>
          <div className="post__content">
            <RichText
              content={unipopia.node.contenu.raw}
              renderers={{
                image: ({ node }) => {
                  const imageUrl = node.children[0].src;
                  return (
                    <img
                      alt={node.children[0].title}
                      src={imageUrl}
                      height={node.children[0].height}
                      width={node.children[0].width}
                      onClick={() => setClickedImage(imageUrl ?? '')}
                    />
                  );
                },
              }}
            />
            {clickedImage && (
            <Lightbox
              large={clickedImage}
              title="Image Title"
              onClose={() => setClickedImage(null)}
            />
            )}
          </div>
        </div>
      ))}
    </article>
  );
}

PostCard.propTypes = {
  posts: PropTypes.arrayOf(
    PropTypes.shape({
      node: PropTypes.shape({
        slug: PropTypes.string.isRequired,
        titre: PropTypes.string.isRequired,
        extrait: PropTypes.string,
        auteur: PropTypes.shape({
          nom: PropTypes.string.isRequired,
        }).isRequired,
        contenu: PropTypes.shape({
          raw: PropTypes.shape({
            children: PropTypes.array.isRequired,
          }).isRequired,
        }).isRequired,
      }).isRequired,
    }),
  ).isRequired,
};

export default PostCard;

Do you see anything that is wrong by any chance?

(sorry, the "code" mode didn't work)

I also tried with ModalImage and cleaned my code but style doesn't work. the weird thing is if I add a console.log to see if the onClick works, it shows nothing.

And if I look at my img src, it looks like this : src="https://media.graphassets.com/resize=width:1754,height:2480/7huO5IwToKhhvYUWcWVA"
Maybe it's because of this type of url?

My component with ModalImage just in case :

import { useState } from 'react';
import PropTypes from 'prop-types';
import { RichText } from '@graphcms/rich-text-react-renderer';
import ModalImage from 'react-modal-image';
import './style.scss';

function PostCard({ posts }) {
  const unipopiaPosts = posts.filter((post) => post.node.categories.some((category) => category.nom === 'Unipopia'));
  const [clickedImage, setClickedImage] = useState(null);

  return (
    <article className="post__block">
      {unipopiaPosts.map((unipopia) => (
        <div key={unipopia.node.slug}>
          <div className="post__title">
            {unipopia.node.titre}
          </div>
          <div className="post__excerpt">
            {unipopia.node.extrait}
          </div>
          <div className="post__content">
            <RichText
              content={unipopia.node.contenu.raw}
              renderers={{
                image: ({ node }) => (
                  <div>
                    <ModalImage
                      alt={node.title}
                      small={node.src}
                      large={node.src}
                      hideZoom
                      onClick={() => setClickedImage(node.src)}
                    />
                  </div>
                ),
              }}
            />
            {clickedImage && (
              <ModalImage
                alt="Clicked Image"
                small={clickedImage}
                large={clickedImage}
                onClose={() => setClickedImage(null)}
              />
            )}
          </div>
        </div>
      ))}
    </article>
  );
}

PostCard.propTypes = {
  posts: PropTypes.arrayOf(
    PropTypes.shape({
      node: PropTypes.shape({
        slug: PropTypes.string.isRequired,
        titre: PropTypes.string.isRequired,
        extrait: PropTypes.string,
        auteur: PropTypes.shape({
          nom: PropTypes.string.isRequired,
        }).isRequired,
        contenu: PropTypes.shape({
          raw: PropTypes.shape({
            children: PropTypes.array.isRequired,
          }).isRequired,
        }).isRequired,
      }).isRequired,
    }),
  ).isRequired,
};

export default PostCard;

The problem with your code is that you're rendering the ModalImage component twice.

You're <RichText /> component should look like this:

  <RichText
    content={unipopia.node.contenu.raw}
    renderers={{
      img: ({ src, width, height, altText }) => (
        <div>
          <img
            src={src}
            alt={altText}
            width={width}
            height={height}
            onClick={() => setClickedImage(src ?? "")}
          />
        </div>
      )
    }}
  />

If you look at your code, you're using image instead of img. You're also rendering ModalImage instead of an image. Please take a look at the example I shared!

Hey there! Sorry to bother you with that, I'm very new to all of this.
I fixed my code and mostly copy/past yours.
Image seens to be clickable now but I have another error in my console, now from Lightbow itself.

Not showing lightbox because no image(s) was supplied
at s (http://localhost:8080/js/main.52bd1cb363c583eab43e.js:17367:3086)
at div
at div
at article
at PostCard (http://localhost:8080/js/main.52bd1cb363c583eab43e.js:6602:20)
at div
at Container (http://localhost:8080/js/main.52bd1cb363c583eab43e.js:6096:23)
at div
at Page (http://localhost:8080/js/main.52bd1cb363c583eab43e.js:6493:23)
at Unipopia (http://localhost:8080/js/main.52bd1cb363c583eab43e.js:7439:67)
at RenderedRoute (http://localhost:8080/js/main.52bd1cb363c583eab43e.js:61205:5)
at Routes (http://localhost:8080/js/main.52bd1cb363c583eab43e.js:61826:5)
at div
at App
at Router (http://localhost:8080/js/main.52bd1cb363c583eab43e.js:61764:15)
at BrowserRouter (http://localhost:8080/js/main.52bd1cb363c583eab43e.js:59827:5)

Maybe I'm just lost and should use something easier for a begginer :/ 

just in case you still have some times to waste, my new component: 

import { useState } from 'react';
import PropTypes from 'prop-types';
import { RichText } from '@graphcms/rich-text-react-renderer';
import Lightbox from 'react-awesome-lightbox';
import 'react-awesome-lightbox/build/style.css';
import './style.scss';
function PostCard({ posts }) {
const unipopiaPosts = posts.filter((post) => post.node.categories.some((category) => category.nom === 'Unipopia'));
const [clickedImage, setClickedImage] = useState('');
return (


{unipopiaPosts.map((unipopia) => (


{unipopia.node.titre}


{unipopia.node.extrait}


{console.log('Contenu brut :', unipopia.node.contenu.raw)}
<RichText
content={unipopia.node.contenu.raw}
renderers={{
img: ({
src, width, height, altText,
}) => (
<img
src={src}
alt={altText}
width={width}
height={height}
onClick={() => setClickedImage(src ?? '')}
/>
),
}}
/>
{clickedImage && (
<Lightbox
large={clickedImage}
title="Image Title"
onClose={() => setClickedImage(null)}
/>
)}


))}

);
}
export default PostCard;

No worries at all. I'm glad it's working, but I'm unsure what's causing this error on the console. Looking at your code, everything seems to be okay.

Hey there! I made a looooooot of tests and found a solution at last. That's not the best and it's not very sexy but at least it works.
I can't use lightbox or anything like that, I can't use RichText either to display images because when I click on it, I will always have the error message "Not showing lightbox because no image(s) was supplied".

But if I add my images as an attached assets instead of inside my content and wrap it in a , it seems to work. I thought it may interest you :)

        <RichText
              content={unipopia.node.contenu.raw}
              renderers={{
                img: ({
                  src, width, height, altText,
                }) => (
                  <a href={`https://media.graphassets.com/${unipopia.node.images}`}>
                    <img
                      src={src}
                      alt={altText}
                      width={width}
                      height={height}
                    />
                  </a>
                ),
              }}
            />