Reputation: 137
I'm kind of new to reactjs and I'm trying to do a bit of clean up. I was wondering how I could use spread attributes for props provided by the new context api? <Today />
and <All />
will basically use the same props and I thought it looked pretty messy.
Here are the lines I wanted to clean up:
<ResultsProvider>
<ResultsContext.Consumer>
{(val) => (
<Switch>
<Route exact path={'/'} render={ (props) =>
<Today
results={val.results}
loading={val.loading}
viewTicket={val.viewTicket}
formatStatus={val.formatStatus}
fetchData={val.fetchData}
formatDate={val.formatDate}
sortResults={val.sortResults}
formatTitle={val.formatTitle}
/>
}/>
<Route path={'/week'} component={Week} />
<Route path={'/all'} render={ (props) =>
<All
results={val.results}
loading={val.loading}
viewTicket={val.viewTicket}
formatStatus={val.formatStatus}
fetchData={val.fetchData}
formatDate={val.formatDate}
sortResults={val.sortResults}
formatTitle={val.formatTitle}
/>
}/>
</Switch>
)}
</ResultsContext.Consumer>
</ResultsProvider>
Upvotes: 4
Views: 4983
Reputation: 281686
Since both the components need to be passed the same props, you can create an object and then pass it to the components using spread syntax like
<ResultsProvider>
<ResultsContext.Consumer>
{(val) => {
const customProps = {
results: val.results,
loading: val.loading,
viewTicket: val.viewTicket,
formatStatus: val.formatStatus,
fetchData: val.fetchData,
formatDate: val.formatDate,
sortResults: val.sortResults,
formatTitle: val.formatTitle
}
return <Switch>
<Route exact path={'/'} render={ (props) =>
<Today
{...props}
{...customProps}
/>
}/>
<Route path={'/week'} component={Week} />
<Route path={'/all'} render={ (props) =>
<All
{...props}
{...customProps}
/>
}/>
</Switch>
}}
</ResultsContext.Consumer>
</ResultsProvider>
Upvotes: 10