1 year ago
#383132
singing sun
Migrating to React - Using Composition instead of Inheritance in React
Hi I need some directions and advices. I have a task to migrate a codebase from javascipt to react.
Lemme explain this project to you
So this project has a quite simple codebase. I draw shapes and objects on a HTML canvas.
Those objects/shapes have some common properties, a few methods like draw
for example: take this code from old codebase
class Square extends Shape{
constructor(height, width, fill,....){
this.height=height
this.width = width
this.context = ...
this.x = ...
this.y = ....
.
.
}
draw(){
....uses canvas context and draws shape using x, y coordinates and stuff
}
resize(){
this.height = ....
}
.
.
.
.
}
Now I have to migrate from this old code and start a fresh new React Project.
Some Problems and Confusions
I read in docs that React doesnt expect us to use Inheritance. It uses Compositon. Can you explain me how can I convert these classes and use compositonn with A little code example. Do I need to create a React Functional Component to replace this class?
- In that functional component there I will use
useState
hook to createheight
,width
, ....etc states and I will re-implement functions likeresize()
useingsetHeight
,setWidth
, etc
- In that functional component there I will use
Do I need to re-implement all data members like this: -
this.height
and other data members of theclass
will be re-implemented usinguseState
? I asked this because I thinkresize()
method needs to written again that will usesetHeight
,setWidth
etc,.. as It will changeheight
state andwidth
state in order to resize shape.
Note that fill
, height
and width
are not props passed to canvas. It is used by a function like draw
and resize
which actually RE-DRAWS in the canvas.
Also I am not moving away from canvas to HTML elements, I am trying to still do canvas, but based in React instead
javascript
reactjs
html5-canvas
0 Answers
Your Answer