lundi 22 janvier 2018

React: Is it bad practice to import a child component directly rather than pass in as a dependency?

I may be over thinking this, but I am curious if importing a child component directly is bad practice with regards to coupling and testing.

Below is a simple example:

import Header from './header.jsx';

class Widget extends React.Component {
    render() {
        return (
            <div>
                <Header></Header>
                <div>{this.props.importantContent}</div>
            </div>
        )
    }
}

To me it looks like there is now coupling between Widget and Header. With regards to testing, I don't see an easy way to mock the Header component when testing the Widget component.

How do other larger React apps handle cases like this? Should I pass Header in as a prop? If using react-redux, I can inject header with the Connect method like below to reduce boilerplate. Is that sound?

import { connect } from 'react-redux';
import Header from './header.jsx';

class Widget extends React.Component {
    render() {
        return (
            <div>
                {this.props.header}
                <div>{this.props.importantContent}</div>
            </div>
        )
    }
}

const mapStateToProps = state => {
  return {
    header: Header
  }
}

export default connect(mapStateToProps)(Widget)

I am interested is simple doing what the community is generally doing. I see that one solution is doing shallow rendering to test on the main part of the component and not the child components using something like Enzyme.

Thoughts or other ideas?

Aucun commentaire:

Enregistrer un commentaire