Next.js - route based modal

后端 未结 2 392
暖寄归人
暖寄归人 2020-12-20 02:33

When using Next.js, I want to show a modal based on a url, on top of another page.

If gallery.js is the page component, I want /gallery/image/123

2条回答
  •  有刺的猬
    2020-12-20 02:55

    If I understand your question correctly you want to add deep links to the individual gallery items. This is possible, but you need a custom server to handle custom routes.

    The first thing you need to do is setup the routes. I shared an example here: using React router with Next JS route.

    const nextRoutes = require('next-routes');
    const routes = (module.exports = nextRoutes());
    
    routes
        .add('gallery', '/gallery')
        .add('gallery-item', '/gallery/image/:image', 'gallery')

    Then you can access this parameter in the getInitialProps method, and render the modal if the image parameter is set:

    import React from 'react';
    import PropTypes from 'prop-types';
    
    export default class Gallery extends React.Component {
        static propTypes = {
            image: PropTypes.string
        };
        
        static getInitialProps({query: {image}}) {
            return {image};
        }
    
        render() {
            const {image} = this.props;
    
            return (
                
    {image && // render modal } // render gallery
    ); } }

提交回复
热议问题