ArrayKnight ArrayKnight - 1 year ago 650
React JSX Question

Adding script tag to React/JSX

I have a relatively straightforward issue of trying to add inline scripting to a React component. What I have so far:

'use strict';

import '../../styles/pages/people.scss';

import React, { Component } from 'react';
import DocumentTitle from 'react-document-title';

import { prefix } from '../../core/util';

export default class extends Component {
render() {
return (
<DocumentTitle title="People">
<article className={[prefix('people'), prefix('people', 'index')].join(' ')}>
<h1 className="tk-brandon-grotesque">People</h1>

<script src=""></script>
<script dangerouslySetInnerHTML={{__html: 'try{Typekit.load({ async: true });}catch(e){}'}}></script>

I have also tried:

<script src=""></script>
<script>try{Typekit.load({ async: true });}catch(e){}</script>

Neither approach seems to execute the desired script. I'm guessing it's a simple thing I'm missing. Can anybody help out?

PS: Ignore the foobar, I have a real id actually in use that I didn't feel like sharing.

Answer Source

Do you want to fetch and execute the script once when this component is mounted into the DOM, or do you want to fetch and execute it every time this component is rendered?

Perhaps try something like this:

    componentWillMount() {
        const script = document.createElement("script");

        script.src = "";
        script.async = true;


but I highly recommend you re-think "why" you are doing it this way.. there is a Typekit package on NPM you could just import/require..

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download