Reputation: 259
I need to be able to pass a function as props to my 'Tasks' component (see code below), but I can't because of the way I've structured my project. Any tips on how I can change {taskItems}
to a Tasks instance, so I can pass props from App.jsx
to Tasks.jsx
, whilst not breaking the rest of my app?
// App.jsx
import React, {useState} from 'react';
import Header from './Header'
import Card from './Card'
import cardData from './cardData'
import Dates from './Dates'
import Tasks from './Tasks'
import Footer from './Footer'
const initialState = [
{
id: 8,
chore: 'wash dishes'
},
{
id: 9,
chore: 'do laundry'
},
{
id: 10,
chore: 'clean bathroom'
}
]
function App() {
const [taskList, setUpdatedTasks] = useState(initialState)
const cardComponents = cardData.map(card => {
return <Card key={card.id} name={card.name} />
})
const taskItems = taskList.map(item => {
console.log(item)
return <Tasks key={item.id} task={item.chore} />
})
const updateHandler = (thing) => {
}
return (
<div>
<Header />
<Dates />
<div className='card-container'>
{cardComponents}
</div>
{taskItems} // how would I change this to an instance of <Tasks/> ?
<div>
<Footer />
</div>
</div>
)
}
export default App;
Upvotes: 1
Views: 66
Reputation: 32492
Actually, this question comes from your mindset, ReactJS is not like you think, every component in a ReactJS project is a function and forget about OOP principles. an instance does not make sense here. you can do it as easy as possible, pass your function just like a prop to the Tasks.jsx
component:
~~~
function App() {
const [taskList, setUpdatedTasks] = useState(initialState)
const cardComponents = cardData.map(card => (
<Card key={card.id} name={card.name} />
));
const taskItems = taskList.map(item => (
<Tasks
key={item.id}
task={item.chore}
func={setUpdatedTasks} // <--- Here
/>
);
});
~~~
Upvotes: 1
Reputation: 150
well, TaskItem is another component inside your App and it should receive the function you want to pass to it as props as well, so it will be like this
// App.jsx
import React, {useState} from 'react';
import Header from './Header'
import Card from './Card'
import cardData from './cardData'
import Dates from './Dates'
import Tasks from './Tasks'
import Footer from './Footer'
const initialState= [
{
id: 8,
chore: 'wash dishes'
},
{
id: 9,
chore: 'do laundry'
},
{
id: 10,
chore: 'clean bathroom'
}
]
function App() {
const [taskList, setUpdatedTasks] = useState(initialState)
const cardComponents = cardData.map(card => {
return <Card key = {card.id} name = {card.name}/>
})
const taskItems = ({updateHandler}) =>
taskList.map(item => {
console.log(item)
return <Tasks key={item.id} task ={item.chore} updateHandler={updateHandler}/>
})
const updateHandler = (thing) => {
}
return (
<div>
<Header/>
<Dates/>
<div className = 'card-container'>
{cardComponents}
</div>
{taskItems} **// how would I change this to an instance of <Tasks/> ?**
<div>
<Footer/>
</div>
</div>
)
}
export default App;
Upvotes: 0