Do objects saved in state/passed as props in React violate the law of Demeter?

77 views Asked by At

so I've started using the law of Demeter recently(heard about it a month ago) and I am currently also learning react.

But let's take this component

function CatImages(props) {
    return props.data.imgSrc.map((cat, index) => (
        <img src={cat} alt="Cat" key={index} />
    ));
}

Where you have a data object that is passed as prop in the component

myData = {
    imgSrc: ['src1', 'src2', 'src3']
}

<CatImages data={myData} />

As far as I understand, imgSrc is a stranger.

Same would happen if you save data in the component state and then access it like this.state.data.imgSrc

One solution would be to pass imgSrc={data.imgSrc} and use it directly as props.imgSrc or save imgSrc in the state directly

Even using a state management system like Redux, will break this law.

I would like to know if the Law of Demeter should be something to worry about when working with objects passed as props or saved in the state so I don't overkill the code.

Thanks

1

There are 1 answers

0
andy mccullough On

If you only pass the data you need to your CatImages component, it should, as far as I can see, hold true to the Law of Demeter?

function CatImages(props) {
    return props.imgSrcs.map((cat, index) => (
        <img src={cat} alt="Cat" key={index} />
    ));
}
myData = {
    imgSrc: ['src1', 'src2', 'src3']
}

<CatImages imgSrcs={myData.imgSrc} />