Great article Kim, I just wanted to add another approach which works better in separating the concerns of managing the state and rendering the style.
Higher order components are great tool to solve this functionality. The function AddClick simply manages the state of one component hence avoiding the trouble of maintaining the state of all the children component in one single component. And the best part is, you can wrap any component with this HOC AddClick and it will get the isClicked prop, hence improving the usability of code.
Here is my alteration to your original code to make HOC work.
constChild=({id,isClicked})=>(<divclassName={isClicked?`highlight`:``}>{`ID ${id} --- I am a child element`}</div>
);functionAddClick(Comp){returnclassHocClickextendsComponent{state={clicked:null}onClick=i=>{this.setState({clicked:!this.state.clicked});}render(){return<divonClick={this.onClick}><Comp{...this.props}isClicked={this.state.clicked}/>
</div>;
}};}constClickableChild=AddClick(Child);classAppextendsComponent{render(){constitems=[1,2,3,4,5].map((id,i)=>{return(<ClickableChildid={id}key={id}/>
);});return(<div>{items}</div>
);}}
A Full Stack Developer who specializes in Javascript Technologies across the whole stack (Node.js, Express, React). Experience building web applications with backend API Systems using Typescript.
HI, thanks for this approach.
I've a little problem.... I want to be able to select only one item from the list of array and return other as false. Is there any workaround to this? Thanks
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Great article Kim, I just wanted to add another approach which works better in separating the concerns of managing the state and rendering the style.
Higher order components are great tool to solve this functionality. The function
AddClick
simply manages the state of one component hence avoiding the trouble of maintaining the state of all the children component in one single component. And the best part is, you can wrap any component with this HOCAddClick
and it will get theisClicked
prop, hence improving the usability of code.Here is my alteration to your original code to make HOC work.
Here is a working example of the app stackblitz.com/edit/react-o8qsku
Thank Kushan 👍,
That's a great way to abstract the click state functionality.
I love how each Child component gets to track its own clicked state (after wrapping it with
AddClick
HoC).I've also gotten a feedback on Reddit and how someone already created a library react-on-off for such a scenario.
I believe that your HoC version is handy when good-enough is just good enough.
Never forget to use prevState. 👍
HI, thanks for this approach.
I've a little problem.... I want to be able to select only one item from the list of array and return other as false. Is there any workaround to this? Thanks