React onClick event handler not working using Next.js
Asked Answered
I

1

8

I'm making a Reddit clone and I'm using Next.js so its server-side rendered. I started without using Next.js and when I learned about it, I immediately switched to it.

I've created a custom _app.js so the header and sidebar exist on every page, and for it to act as the topmost component to hold application state. The later isn't quite working out.

Here's .project/src/pages/_app.js:

import App, { Container } from 'next/app';

// Components
import Header from '../components/Header/Header';

const MainLayout = props => (
  <React.Fragment>
    <Header
      isSidebarOpen={props.isSidebarOpen}
      sidebarToggle={props.sidebarToggle}
    />
    {props.children}
  </React.Fragment>
);

export default class MyApp extends App {
  static async getInitialProps({ Component, router, ctx }) {
    let pageProps = {};

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
    }

    return { pageProps };
  }

  state = {
    isSidebarOpen: true
  };

  sidebarToggle = () => {
    this.setState({ isSidebarOpen: !this.state.isSidebarOpen });
  };

  render() {
    const { Component, pageProps } = this.props;
    return (
      <Container>
        <MainLayout
          isSidebarOpen={this.state.isSidebarOpen}
          sidebarToggle={this.sidebarToggle}
        >
          <Component {...pageProps} />
        </MainLayout>
      </Container>
    );
  }
}

The issue I'm having is, isSidebarOpen and sidebarToggle are being passed to exactly where I need them – they show up in the console – but the onClick handler doesn't activate and if I change isSidebarOpen, it doesn't take effect until I restart the server. I used this approach before using Next.js and it worked as expected.

How can I achieve what I'm trying to do? I've read the docs, searched Google and Stack Overflow. I even checked issues on their repo without luck. I suspect it to be something to do with a custom _app.js, as the props are passed down correctly.

Implacental answered 26/5, 2018 at 13:26 Comment(0)
R
1

One possibility might be to define your sidebarToggle function within the component you are using.(Maybe because calling it inside Component the code might be running in _app.js instead of your component this is a big maybe! but worth a try)

Here _app.js is a wrapper around your application and I don't think it is suited to be used at the topmost component to hold state. Better to make a simple react root Component do that!

Radiolucent answered 16/8, 2019 at 15:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.