Unfortunately, I haven't experienced enough with React to find something that could be useful. By creating this article, I was thinking more about use-cases related to the inner logic of your application, rather than something bound to a framework in specific.
But since React can be used with classes, you could make your own component class, for instance FetchableComponent to reuse api calls for instance (yeah I know, I'm giving the answer, it's too tempting).
importReactfrom"react";importReactDOMfrom"react-dom";classFetchableComponentextendsReact.Component{constructor(){super();returnnewProxy(this,{get(target,property){if(property==="api"){returnendpoint=>fetch(`https://jsonplaceholder.typicode.com/${endpoint}`).then(response=>{if(response.ok){returnresponse.json();}thrownewError("unable to fetch the api");});}returntarget[property];}});}}classUsersListextendsFetchableComponent{constructor(){super();this.state={users:[]};}componentDidMount(){this.api("users").then(users=>{this.setState({users});});}render(){return(<div><h1>Users</h1><ul>{this.state.users.map(({id,username})=>(<likey={id}>{username}</li>))}</ul></div>);}}ReactDOM.render(<UsersList/>,document.getElementById("users"));
In this case, you could see FetchableComponent like some sort of Trait like in PHP. Except you cannot use multiple trait like in PHP in this case since it is an extend. But I think you get the idea.
I haven't done React for a while so pardon my mistakes if there are any. What is important is the idea behind Proxies and React. I hope that answer your question!
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.
can you give some example in react js
Hi Nahid and thanks for your comment!
Unfortunately, I haven't experienced enough with React to find something that could be useful. By creating this article, I was thinking more about use-cases related to the inner logic of your application, rather than something bound to a framework in specific.
But since React can be used with classes, you could make your own component class, for instance
FetchableComponent
to reuse api calls for instance (yeah I know, I'm giving the answer, it's too tempting).In this case, you could see
FetchableComponent
like some sort of Trait like in PHP. Except you cannot use multiple trait like in PHP in this case since it is an extend. But I think you get the idea.I haven't done React for a while so pardon my mistakes if there are any. What is important is the idea behind Proxies and React. I hope that answer your question!