How to rewrite when a class component extends from another class? Parameters in the constructor is what makes me unsure how to handle. Anyone with ideas?
Code example.
class Animal extends React.Component {
constructor(name, action, addKeywords = [], addHashtag = []) {
super();
this.name = name;
this.action= action;
this.currentUser = new CurrentUser();
this.keywordList = FILTER_BY_KEYWORDS.concat(addKeywords );
this.hashtagList = addHashtag;
}
nameChange(name) { ... }
}
class Lion extends Animal {
render() {
return <Item name={this.nameChange} />
}
}
While inheritance was never encouraged in class components, sometimes we cannot choose the shape of the legacy code that we want to migrate to Hooks. Each old component will be different and I don't encourage anyone to write following code when working on a new project using React Hooks.
That said, following is the most "direct translation" of that particular class structure from the question into a function component with hooks that I can think of:
function useAnimal(name, action, addKeywords = [], hashtagList = []) {
const self = React.useRef()
if (!self.current) {
// simulate synchronous constructor method, using the initial prop values
self.current = {
name,
action,
currentUser: new CurrentUser(),
keywordList: FILTER_BY_KEYWORDS.concat(addKeywords),
hashtagList,
nameChange: (name) => { ... }
}
}
return self.current
}
function Lion({name, action, addKeywords, addHashtag}) {
const {nameChange} = useAnimal(name, action, addKeywords, addHashtag)
return <Item name={nameChange} />
}