Ad

Passing Main Component State To Another Component Error

- 1 answer

What I want to do is take the list that is in the main component state and pass it to the List component as a prop.

It is not working and I get the 'state' is not defined error. Don't know why. This is my code.

import React from 'react';
import List from './components/List';

import './App.css';

function App() {

  state = {
   list: [
     {
       id: 1,
       place: 'Doesn't matter',
       reserved: false
     },

   ]
 } 
 return (
   <div className="App">
    <List  list={this.state.list} />
   </div>
 );
}

export default App;

list component List.js

import React from 'react';



function App() {
 return (
   <div className="App">
    <h1>app</h1>
   </div>
 );
}

export default App;
Ad

Answer

You may follow this approach too, I mean you can convert your App function to a component class where you can use state

App.js

import React, { Component } from "react";
import List from "./list";

class App extends Component {
  state = {
    list: [
      {
        id: 1,
        place: "Doesn't matter",
        reserved: false
      },
      {
        id: 2,
        place: "Matter",
        reserved: true
      }
    ]
  };

  render() {
    return (
      <div className={"App"}>
        <List list={this.state.list}></List>
      </div>
    );
  }
}

export default App;

And then make your list as functional component where you just want to play with props

list component

import React from "react";
const List = ({ list }) => {
  return (
    <div>
      <ul>
        {list.map(l => (
          <li key={l.id}>{l.place}</li>
        ))}
      </ul>
    </div>
  );
};

export default List;

Hope it will help you

Ad
source: stackoverflow.com
Ad