Natalie
Natalie

Reputation: 553

JS not running on Gatsby

I'm trying Gatsby for the first time to build a blog. I'm using the Gatsby Starter Blog as a base.

I want to add some javascript to animate some text, and just as a quick test I've added the below to my html.js file:

<script
      dangerouslySetInnerHTML={{
        __html: `
                var name = 'world';
                console.log('Hello ' + name);

                console.log('hey');

                const phrases = [
                    'aaa',
                    'bbb',
                    'ccc'
                ];

                const el = document.getElementById('bio__subtext');

                el.innerHTML = 'hi';

            `,
      }}
    />

However this is throwing the following error in my console: (index):15 Uncaught TypeError: Cannot read property 'innerHTML' of null

The ID is correct, and exists in my Bio.js file:

class Bio extends React.Component {
  render() {
    return (
      <div id="bio">
        <div className="bio_wrapper">
            <img
              src={profilePic}
              alt={'NdW'}
            />
            <p>
              Hi, I'm Natalie!<br />
              I <span id="bio__subtext"></span><br/>
              <span className="about_button"><a href="/">Find out more</a></span>
              <a href="#" target="_blank">GH</a>
              <a href="#" target="_blank">TW</a>
            </p>
        </div>
      </div>
    )
  }
}

I assume this is because the JS is trying to run before Bio.js has finished.. but how do I tell the JS to "wait"? If I try including the JS in the Bio.js file, it fails to compile.

Adding document.addEventListener("DOMContentLoaded", function(event) { doesn't help either.

Upvotes: 2

Views: 985

Answers (1)

ksav
ksav

Reputation: 20821

There shouldn't be any need to select anything in the DOM like you are attempting with the use of document.getElementById('bio__subtext').

You can declare variables right in your component where they are needed or pass then into the component via a prop from a higher context (a page or another component).

class Bio extends React.Component {
  render () {
    const name = 'Natalie'
    const phrases = [
      'Cowabunga',
      'Its Ninja Time',
      'Booyakasha'
    ]
    return (
      <div id="bio">
        Hi, I'm {name}!<br />
        Some of my favourite phrases are:
        <ul>
          {phrases.map(phrase => <li>{phrase}</li>)}
        </ul>
      </div>
    )
  }
}

Upvotes: 1

Related Questions