I have a file with multi component that I want to export and connect all to redux, how can I do this?
Connect wrapper need to export default, but I have multi component.
I have a file with multi component that I want to export and connect all to redux, how can I do this?
Connect wrapper need to export default, but I have multi component.
You don't have to export default to use connect. You can connect multiple components within the same file, with or without exporting them. Although I would recommend only placing 1 component per file
import React from 'react'
import { connect } from 'react-redux'
// This also works without the export statement
export const Comp1 = connect(
state => ({
someProp: state,
})
)(({ someProp }) => (
<div>
<h1>Comp 1</h1>
<p></p>
</div>
))
const Comp2 = connect(
state => ({
someProp: state,
})
)(({ someProp }) => (
<div>
<h1>Comp 2</h1>
<p></p>
</div>
))
export default Comp2
redux
doesn't provide any default export. always you connect to redux using react-redux
whenever you need.
If you want some of the dispatch
or state
pass on your child component through parent component then connect redux
on your parent component and then destructure
the props
at child component. then all dispatch
and state
available on parent and child component.
import React from 'react'
import { connect } from 'react-redux'
import Component1 from './component1'
import Component2 from './component2'
import { sampleDispathFunction } from './actions'
const WrapperComponent = (props) => {
return <div>
<Component1 {...props} />
<Component2 {...props} />
</div>
}
const mapStateToProps = (state) => ({
data: state.data,
customer: state.customer
});
const mapDispatchToProps = (dispatch) => ({
sampleDispathFunction: (data) => dispatch(sampleDispathFunction(data))
});
export default connect(mapStateToProps, mapDispatchToProps)(WrapperComponent);