Ad
Passing Main Component State To Another Component Error
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
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad