Learner
Learner

Reputation: 119

Reactjs: why is this not working in class component but working in functional component

why is this not working in the class component but working in the functional component?

Functional Component(working)

export default function App() {
  const initCols = [
    {
      name: 'name',
    },
  ];
  const [cols, setCols] = useState(initCols); // works
}

ClassComponent(not working)

class testclass extends Component {
  const initCols = [
  {
    name: "name"
  }];
  state = {cols: initCols}   // donot work
}

Upvotes: 0

Views: 69

Answers (2)

Sowam
Sowam

Reputation: 1736

You cannot define const values in class component because it is a class but you can do it that way:

 state = {
    cols: [
      {
        name: "name"
      }
    ]
  };

Is there any reason that you have to have it in const variable?

You can also define it before a component and then use it like:

const initCols = [
{
    name: "name"
}];

class testclass extends Component {
 state = {cols: initCols} 

Upvotes: 1

Learner
Learner

Reputation: 119

// This works

const initCols = [
{
    name: "name"
}];
class testclass extends Component {
state = {cols: initCols}
....

Upvotes: 0

Related Questions