Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Current React JS : 'state' is not defined no-undef

I am learning ReactJS and I came across this error 'state' is not defined no-undef Your assistance on where am going wrong. I have the current React "react": "^16.8.6". I tried adding in this.state instead I got: Line 1: 'Component' is defined but never used no-unused-vars Line 8: Do not mutate state directly. Use setState() react/no-direct-mutation-state

App.js

import React, { Component } from 'react';
import './App.css';
import Todos from './Components/Todos';



function App() {
  state = {
    todos:[
      {
        id:1,
        title: "Study File Structure",
        completed:false
      },
      {
        id:2,
        title: "Create Component",
        completed:false
      },
      {
        id:3,
        title: "Study State",
        completed:false
      }
    ]
  }

  return ( 
    <div className="App">

      <h1>Hello</h1>
      <Todos/>
    </div>
  );
}

export default App;
like image 220
saiyan101 Avatar asked May 20 '19 19:05

saiyan101


2 Answers

Replace function App() { with class App extends Component{. That will get you going in the right direction, and wrap the return in a render method, like so:

class App extends Component{
  state = {
    todos:[
      {
        id:1,
        title: "Study File Structure",
        completed:false
      },
      {
        id:2,
        title: "Create Component",
        completed:false
      },
      {
        id:3,
        title: "Study State",
        completed:false
      }
    ]
  }

  render(){
    return ( 
      <div className="App">

        <h1>Hello</h1>
        <Todos/>
      </div>
    );
  }
}

export default App;
like image 63
Ted Avatar answered Sep 23 '22 17:09

Ted


You can simply use React hooks. Append the state with React so you have React.state.

import React, { Component } from 'react';
import './App.css';
import Todos from './Components/Todos';



function App() {
  React.state = {
    todos:[
      {
        id:1,
        title: "Study File Structure",
        completed:false
      },
      {
        id:2,
        title: "Create Component",
        completed:false
      },
      {
        id:3,
        title: "Study State",
        completed:false
      }
    ]
  }

  return ( 
    <div className="App">

      <h1>Hello</h1>
      <Todos/>
    </div>
  );
}

export default App;

Now when you need to call anything from the state, classes use this.state.todos but in your case, use React.state.todos

Let me know if this helps. :)

like image 21
mw509 Avatar answered Sep 21 '22 17:09

mw509