bsky
bsky

Reputation: 20222

Bootstrap modal in React

I am trying to create a bootstrap modal in React according to the instructions from here.

I created a new class with the following content;

class Button extends React.Component {
  state = {
    isShowingModal: false
  }
  openModal = () => {
    this.setState({isShowingModal: true});
  }
  render() {
    return (
      <a onClick={this.openModal}>
        Button Text
        {this.state.isShowingModal ?
          <ModalComponentHere/>
        : null}
      </a>
    )
  }
}

However, when I try building the project I get the following error:

 Parse Error: Line 6: Unexpected token = while parsing file

The error shows up on the line:

state = {

Why does this error appear?

I don't have much experience with JavaScript but this to me looks like correct syntax.

Upvotes: 0

Views: 231

Answers (1)

Jonny Buchanan
Jonny Buchanan

Reputation: 62783

If you paste your code into the Babel online REPL, you'll notice that it won't transpile until you check the "Experimental" box.

state = {
  isShowingModal: false
}

This syntax within a class body isn't (currently) valid JavaScript syntax, it's an experimental proposal for syntax to be included in a future version of the language.

Babel supports transpiling experimental features to run in today's JavaScript.

This one is es7.classProperties, which is a Stage 0 proposal, so in order to use it you must tell Babel you either want to use Stage 0 features or this one in particular (it defaults to Stage 2).

The above link covers one way to do this, but another common way is to create a .babelrc file which configures the stage of experimental features you want to use, e.g.

{
  "stage": 0
}

Check out React's ES6 Classes documentation for examples of how to create React components by extending React.Component, but without the experimental syntax.

This should be equivalent to what your code was intended to do:

class Button extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isShowingModal: false
    }
    this.openModal = () => {
      this.setState({isShowingModal: true})
    }
  }
  render() {
    return (
      <a onClick={this.openModal}>
        Button Text
        {this.state.isShowingModal ?
          <ModalComponentHere/>
        : null}
      </a>
    )
  }
}

Upvotes: 2

Related Questions