How to add Javascript to a React Component

What I thought

I created an HTML/Sass/Jquery site and decided to turn it into a React app. I learned how to turn HTML into JSX, how to import dependencies, how to link the stylesheet, and how to work with props. With all that info I assumed I knew how to link the Javascript to a component… I was wrong. This is what I did below.

import React from "react";
import "./styles.css";

function sum() {
  return 2 + 2;
}

function MathComponent() {
  sum();
  return (
    <div className="component1">
      <ComponentPiece />
      <ComponentPiece />
      <ComponentPiece />
    </div>
  );
}

export default MathComponent;

You see where I went wrong just assuming stuff? Yep, calling the function. I knew functions needed to be called AFTER the html, but I also knew I couldn’t call a function after a return. So where does this function go???

What I learned

After hours of googling, and “not” finding my answer, I eventually realized I’ve been seeing and ignoring the answer the whole time. This became one of my many lessons on not assuming things. I just KNEW it was as simple as importing and placing the code somewhere, but nope. I needed to add componentDidMount to my code and adjust the layout of it all. This became the correct answer below.

import React, {Component} from "react";
import "./styles.css";

class MathComponent extends Component{
   componentDidMount(){
     function sum() {
     return 2 + 2;
     };
   }

   render(){
     return (
       <div className="component1">
         <ComponentPiece />
         <ComponentPiece />
         <ComponentPiece />
       </div>
     );
   }
}

export default MathComponent;

Suddenly all my Javascript worked as it should! I was in awe of how long I ignored this answer simply because it wasn’t something I’d seen yet and convinced myself it couldn’t be what I was looking for.

What is componentDidMount?

componentDidMount is a hook that gets invoked right after a React component has been rendered. So how does a function that can’t be placed after the return successfully run after the return? This is how. It can also run more than once if the prop keeps changing. Two others I discovered were componentDidUpdate and componentWillUnmount. Plan on looking more into those later.

Leave a Reply