#301DaysOfCode – Learning React – Week 3

Components

Continuing on with components, the render() function must return something, but you are not limited to just returning some JSX. You are also able to place calculations in this function that should happen before the component renders.

Here we calculate the value of Pi using the JavaScript Math Object property, Math.PI, and assign it to a const. We can then use that calculation within the curly braces {} to render the correct value.

class MyMathClass extends React.Component {
  render() {
    const p = Math.Pi;
    return <p>Pi is equal to {p}<p>;
  }
}

You should, however, still place the calculation inside and not outside of the render function. Placing the calculation outside of the render function will attempt to add it to the class declaration.

Conditionals

Not unsurprisingly, you can use a conditional statement to help render your component. This is useful if you’d like to render different JSX depending on some condition.

In the example below, we print out “Right now I will not eat” if we alreadyAte (const based on the Math.random() function), otherwise it will print out “Right now I will eat” within paragraph tags.

Remember to keep your variable in the curly braces {}!

const alreadyAte = Math.random() >= 0.5;

class Food extends React.Component {
  render() {
    let decision;

    if (alreadyAte) {
      decision = "not eat";
    } else {
      decision = "eat";
    }

    return <p>Right now I will {decision}.<p>;
  }
}

Wrap-up

This past week I was able to learn more about making React Components render calculations, and conditional content. I also started to learn about this, which is heavily used in React, but in general in JavaScript.

Since it is more of a JavaScript topic, I’d like to dedicate a post to just that – heh. I’ll still be demonstrating it’s use within the React realm. It’ll be more of a JavaScript post and less of a React post, but I feel that having at least a basic understanding of this is very important to understanding React. Enjoy your week!