DEV Community

Discussion on: SpaceInvaders with only JavaScript and CSS!

 
nicolalc profile image
Nicola

I think you might not access the component variable, but you must define variables as component properties, and set them when you declare a component instance.

For example:

interface WelcomeProps = {
  name: string;
  color: string;
}
class Welcome extends React.Component<WelcomeProps> {
  constructor(props) {
    super(props);
  }
  render() {
    const {props} = this;
    return <h1 color={props.color || '#000'}>Hello, {props.name}</h1>;
  }
}
[...]
const element = <Welcome name="Mario" color="red" />;

You don't need to access to the component variables if you only need to keep it dynamic, use react props to handle component variations.

Thread Thread
 
drmandible profile image
DrMandible

Thanks! This gives me something to chew on. I keep seeing articles that are refactoring the kind of code you're showing me into hooks and ditching the constructor and super props. So I haven't even looked into that functionality because I've been trying to use hooks for everything. But perhaps yours is the more straightforward way.

I see you're using typescript too. I should probably start doing that.

Thread Thread
 
nicolalc profile image
Nicola

I think typescript is a must, If you don't know JS well it could be a mess to handle. Also, the major frameworks (and not) like Angular, React and Vue uses Typescript as the default language. It could lead you to a fantastic Object-driven Javascript world, where you can reduce the size of your written code and improve your code without wasting time debugging around for hours!

I suggest you to start with the tutorials here and to learn also what nodejs is and how to use it. Take a look also on what npm is and what is a node package before starting with typescript.

I'm creating a TS version of this SpaceInvaders to improve the project readability.

Thread Thread
 
drmandible profile image
DrMandible

Awesome! I've hooked up a node.js backend to my react app as a test / proof of concept. It's a hassle. So anything to make that easier is fantastic.