DEV Community

Discussion on: SpaceInvaders with only JavaScript and CSS!

drmandible profile image
DrMandible

I am but I'm still learning too. When I import a React component I'm often unable to access the variables inside that component and I don't know why or when that happens. I'm sure it's something obvious.

My ideal developers environment would have a color coded graph of all my variables, where they were declared, their current values, and what their scope is. Passing values - especially state/context - are an endless source of frustration for this budding developer. I find myself making bloated functions just so I can write something without having to stop and debug for an hour just to pass state.

Thread Thread
nicolalc profile image
Nicola Author

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 Author

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.