2

I am trying to get access to a React DOM element 'id' from an external script file. I believe my script is being imported correctly as console.log('test') from the file is working, though console.log(myDiv) returns null.

How can I achieve this in React?

// COMPONENT

import './../data/script.ts';

  render() {
    return (
        <div id='targetDiv'>
          <p>{This will be populated from my external script file...}</p>
        </div>
    );
  }

// SCRIPT

  var myDiv = document.getElementById('targetDiv');
  console.log(myDiv);
2
  • Your script might just run too early, console.log before the target dom is mounted. Commented Apr 23, 2019 at 5:48
  • @hackape you were correct thanks. The script was executing before my element was mounted and therefore returning null, I have posted my solution below. Commented Apr 24, 2019 at 2:06

1 Answer 1

1

To fix the issue I needed to import my external script as a function, and then call the function after the component mounted:

// COMPONENT

import { myScript } from './../data/script';

  componentDidMount() {
    {
      myScript();
    }
  }

  render() {
    return (
        <div id='targetDiv'>
          {My script now renders correctly inside the div}
        </div>
    );
  }

// SCRIPT

  var myDiv = document.getElementById('targetDiv');
  const d = document.createElement('p');
  myDiv.appendChild(d);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.