javascripthtmlreactjsdocusaurusstatic-generator

React event handler not executing on Docusaurus page


Overview

In my custom Docusaurus page, a simple button event handler does not execute upon click. The file is in the form of a React component, as is the norm for Docusaurus pages.

What I did

1) I set up my Docusaurus application using docusaurus-init, as advertised on Docusaurus' GitHub page (see https://www.npmjs.com/package/docusaurus-init)

2) I added a custom page as described here https://docusaurus.io/docs/en/custom-pages. I.e., I added a JS file to the pages/ folder.

The custom page code

This is the entirety of the code for the page. The code within the React component is copied from a React example found in the docs. I added the console.log statements in the handlers.

const React = require('react');

const CompLibrary = require('../../core/CompLibrary.js');

class SignUp extends React.Component {
    constructor(props) {
        super(props);
        this.state = {value: ''};

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        console.log("Change occurred!");
        this.setState({value: event.target.value});
    }

    handleSubmit(event) {
        console.log("Submit occurred!");
        alert('A name was submitted: ' + this.state.value);
        event.preventDefault();
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
            <label>
            Name:
            <input type="text" value={this.state.value} onChange={this.handleChange} />
            </label>
             <input type="submit" value="Submit" />
            </form>
    );
    }
}

module.exports = SignUp;

Output I expect

An alert should pop up, and output should appear in the console. Because of event.preventDefault(), page should not be refreshed.

What happens

The input field as well as the button shows up just fine. I type some text in the input field and hit submit. Input field goes blank, no alert, no output in console (neither in client or on server). It appears a refresh took place, which event.preventDefault() apparently did not prevent.


Solution

  • Hi Docusaurus maintainer here.

    This is not a bug. In v1, React is used as a rendering engine, and the output of the build step is just HTML. There's no React runtime shipped to clients, hence event handlers would not work.

    You will need to write script tags in your React component to get this to work. This is an example.

    You should try Docusaurus 2 if you need to build rich websites. Your code will work as intended there.