How to write constructor to set state and change state in next js

Viewed 2845

Hi I am building one next js app I have build component components/search_location.js

constructor(props) {
    super(props);
    this.state = {locations: props.locations};
  }
export default function SearchLocation({locations}){
return(
   <div>
   <h1></h1>
   </div>
)
}

But with above code I am getting error saying

SyntaxError: /Users/search_project/components/search-location.js: Unexpected token, expected ";" (4:17)

 export default function SearchLocation({locations}){

  constructor(){
              ^
    this.state = {
           data: 'www.javatpoint.com'
  }

I want to set state and then onclick of some button I want to change state as well, Can someone please suggest me how to do this?

1 Answers

You have a syntax error, constructor is something that is available only in javascript classes.

You should change your exported component from functional component to class component.

It should looks like this:

import React from 'react';

export default class extends React.Component {
  constructor() {
    this.state = {
      data: 'www.javatpoint.com',
    };
  }

  render() {
    return <div>Content here</div>;
  }
}
Related