11

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.

Mohsen
  • 1,415
  • 1
  • 13
  • 26
  • 1
    You are not forced to export default something in Redux. it's a choice. You can do named export and everything should works. – Ehsan Apr 06 '19 at 06:30

2 Answers2

16

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
Jap Mul
  • 17,398
  • 5
  • 55
  • 66
-1

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);
Ikram Ud Daula
  • 1,213
  • 14
  • 21