30 Days Of JavaScript

Day 30: React

Lesson 3: Props

Let's pretend this is a really, really simple game. Click the button enough times and you win the game. Let's say 5 times.

When count === 5 we show a message saying You Win.

If they keep clicking and hit 7 then we swap the message to say You Loose.

A bit of a rubbish game I will admit, however it will let us learn about making new components in React and also conditional display.

Let's create a <Result /> component to decide which message to show.

Right click on 'src' on the file browser in StackBlitz and add a new file called Result.jsx. You can use .js or .jsx for component extensions - it doesn't matter.

Put this in to your Result.jsx file.

1import React from "react";
2
3export function Result() {
4  return <div>Result: </div>;
5}

I have a very strong opinion that with React components we should not use default export. So rather than declaring this component as:

1export default function Result() {

I have instead written it as:

1export function Result() {

This means it is a named export and when you import it in other files, you have to use it's name. With a default export you can rename it when you import it, which, over time, makes codebase maintenance a nightmare.

If you find yourself on a codebase where using the default is the convention, then by all means stay with it but be strict with yourself, don't rename default exports when you import them.

You can now use Result in App.js. Add this line to the top of App.js.

1import { Result } from "./Result";

Then on the line below button add this line:

1<Result />

You will now see 'Result:' in the UI.

We can pass properties, short hand as props, into any React component. We are going to pass count in to <Result /> so it can determine what to show.

Change your JSX to this.

1<Result count={count} />

You don't need to name the prop (the bit to the left of the =) the same as what you are passing in, it just happens in this case it makes the most sense. score={count} would have worked just as well I suppose.

This is now accessible inside Result.

So let's access it, change the code to this:

1import React from "react";
2
3export function Result(props) {
4  const count = props.count;
5
6  let result = "Keep playing";
7
8  if (count >= 5) {
9    result = "You win! Keep going?";
10  }
11
12  if (count >= 7) {
13    result = "You loose! Too far 😔";
14  }
15
16  return <div>Result: {result}</div>;
17}

Outline

Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co