Petr Tomášek
Petr Tomášek

Reputation: 1438

React component is undefined in html script tag

I need to render React component in my view (html file). I'm using webpack 1 and getting error of component undefined. I tried to use window.component, but it didn't work too. If I use RenderDOM inside my component, all works well.

My component:

export class SmallCart extends BaseComponent {
  ...
  render() {...}
}

Webpack 1 config:

var ExtractTextPlugin = require("extract-text-webpack-plugin");
var BowerWebpackPlugin = require('bower-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var webpack = require('webpack');

module.exports = {
    devtool: 'source-map',
    entry: {
        ...
        myComponent: "./wwwroot/js/es6/SmallCart/SmallCart.jsx",
        ...
    },

    output: {
        path: __dirname + "/dist",
        filename: '[name].js',
        chunkFilename: '[id].chunk.js'
    },
    module: {
        loaders: [
            {
                test: /\.(png|jpg|gif|ico)$/,
                loader: "file-loader?name=assets/[name]-[hash:6].[ext]"
            }, {
                test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: "url-loader?limit=10000&minetype=application/font-woff&name=assets/[name]-[hash:6" +
                        "].[ext]"
            }, {
                test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: "file-loader?name=assets/[name]-[hash:6].[ext]"
            }, {
                test: /\.scss$/i,
                loader: ExtractTextPlugin.extract(['css-loader?-autoprefixer!postcss-loader', 'sass'])
            }, {
                test: /\.css$/i,
                loader: ExtractTextPlugin.extract(['css-loader?-autoprefixer!postcss-loader'])
            }, {
                test: /\.(js|jsx)$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015', 'react']
                }
            }
        ]
    },
    progress: true,
    resolve: {
        modulesDirectories: ['node_modules'],
        extensions: ['', '.json', '.js']
    },

    externals: {
        jquery: "jQuery",
        react: "React",
        reactDOM: "ReactDOM"
    },

    plugins: [
        new webpack.ProvidePlugin({'window.Nette': 'nette-forms', 'window.jQuery': 'jquery', jQuery: 'jquery', $: 'jquery'}),   

        new webpack
            .optimize
            .CommonsChunkPlugin({
                filename: "commons.js", name: "commons",

            }),

        new ExtractTextPlugin("frontend.css"),               
    ]
}

And in my view I have this:

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react.js" charset="utf-8"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.5.4/react-dom.min.js" charset="utf-8"></script>
      <script type="text/javascript" src="/dist/commons.js" charset="utf-8"></script>
    <script type="text/javascript" src="/dist/SmallCart.js" charset="utf-8"></script>
<script type="text/javascript">
    window.data_for_react = {};        
    ReactDOM.render(React.createElement(SmallCart, { dataSource : data_for_react}, document.getElementById('box-to-rendering'))); 
</script>            

But in render method is component undefined. What is wrong? Is possible render component in view?

Thank you for your time.

EDIT

Ok, now I try use window.SmallBasket and webpack config update to:

  ...
 new webpack
        .optimize
        .CommonsChunkPlugin({
            names: [
                "commons"
            ],
            minChunks: Infinity
        }),
    ...

And it works. But I still cannot solve it without window property.

Upvotes: 2

Views: 1014

Answers (1)

OneNeptune
OneNeptune

Reputation: 913

Try putting all your react code from your view in something like this:

document.addEventListener('DOMContentLoaded', () => {

//... your ReactDOM.render stuff here

};

You need to wait for the DOM elements to load before you can getElementById.

Upvotes: 1

Related Questions