jsonreactjslightboxreact-image-lightbox

Dynamic lightbox gallery from JSON


I have this URL that is feched succefully by Axios

const URL_INTERIORES = 'http://localhost:3001/interiores';

I installed the react-image-lightbox from npm and it gave to me default images configured in array.

const images = [
  '//placekitten.com/1500/500',
  '//placekitten.com/4000/3000',
  '//placekitten.com/800/1200',
  '//placekitten.com/1500/1500',
];

I would like to change the default array to get the images from the db.json file to come into images's lightbox. How can I solve it? Here is the rest of the code, with the 'react-image-lightbox' configuration:

class Interiores extends Component {
  constructor(props) {
    super(props)
    this.state = {
      interiores: [],
      photoIndex: 0,
      isOpen: false
    }

  }

  componentDidMount() {
    axios.get(URL_INTERIORES)
      .then(res => {
        this.setState({ interiores: res.data })
      })
  }

  render() {
    const { photoIndex, isOpen } = this.state;
    return (
      <div>
        <button type="button" onClick={() => this.setState({ isOpen: true })}>
          Open Lightbox
        </button>

        {isOpen && (
          <Lightbox
            mainSrc={images[photoIndex]}
            nextSrc={images[(photoIndex + 1) % images.length]}
            prevSrc={images[(photoIndex + images.length - 1) % images.length]}
            onCloseRequest={() => this.setState({ isOpen: false })}
            onMovePrevRequest={() =>
              this.setState({
                photoIndex: (photoIndex + images.length - 1) % images.length,
              })
            }
            onMoveNextRequest={() =>
              this.setState({
                photoIndex: (photoIndex + 1) % images.length,
              })
            }
          />
        )}           

      </div>
    )
  }
}    

export default Interiores;

And here is my db.json file.

 "interiores": [
    {
      "text": "introduction text here",
      "images": [
        "int_01_thumb.jpg", "int_02_thumb.jpg", "int_03_thumb.jpg", 
        "int_04_thumb.jpg",  "int_05_thumb.jpg",  "int_06_thumb.jpg",  
        "int_07_thumb.jpg",  "int_08_thumb.jpg",  "int_09_thumb.jpg"
      ]
    }
  ],

Solution

  • I've never worked with such library, so I might be missing something, but would an alternative like this work?

    render() {
        const { interiores, photoIndex, isOpen } = this.state; // Added 'interiores'
    
        // Link to static root and make a relative path for each iamge
        const staticRoot = '//localhost:3001/interiores/'
        const images = interiores[0].images.map(i => staticRoot + i)
    
        // Rest of your code
    }    
    

    Once you have the file names, just link them to your static files/images path and map over the image array.