Next.js - route based modal

帅比萌擦擦* 提交于 2019-12-29 08:16:11

问题


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/1232132 to display a modal with an image, on top of the gallery page.

Is that possible?


回答1:


yeah !!! you can use window.history.pushState for change url without switching in components.

// Modal Button
<button onClick={() => {
    this.setState({ modal: true });
    window.history.pushState("","","/gallery/image/img_1233")
}}>
    Open Modal
</button>

//Link Button
<Link href="/gallery/image/img_1233">
    <a>Open Page</a>
</Link>

complete example here : https://github.com/singlepageprogrammer/react-modal-route-example




回答2:


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 (
            <div>
                {image &&
                    // render modal
                }
                // render gallery
            </div>
        );
    }
}


来源:https://stackoverflow.com/questions/51363962/next-js-route-based-modal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!