2

I've tried to use reactJS inside .net framework MVC application.

View:

<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.js"></script>

<div id="root"></div>
@Scripts.Render("~/Scripts/ReactJS/test.jsx")

test.jsx:

import React from 'react';

import ReactDOM from 'react-dom';

const App = () => <div>Hello world!</div>;
ReactDOM.render(<App />, document.getElementById("root"));

Message is not shown and the error is:

test.jsx:2 Uncaught SyntaxError: Cannot use import statement outside a module

I don't understand why is this not working. I have included both react libraries and babel library.

FrenkyB
  • 6,625
  • 14
  • 67
  • 114
  • Not marking as duplicate because I am not sure if it is, but this may be your issue: https://stackoverflow.com/questions/58357941/cannot-use-import-statement-outside-a-module – jwatts1980 Nov 18 '19 at 03:27
  • 3
    Did you ever have any luck with this? I'm running into a very similar scenario with ReactJS.Net and .NET Core sample app. – John Spiegel Mar 07 '20 at 01:03

2 Answers2

0

you can bundle up your file in BudleConfig.js

 bundles.Add(new BabelBundle("~/bundles/test").Include(
           ("~/Scripts/lib/Component/test.jsx"),
           ));

and then import this Bundler in your CSHTML inside Script

 @Scripts.Render("~/bundles/test");
 ReactDOM.render(
        React.createElement(test),
        document.getElementById('root')
    );

and you are good to go like that you can create and import JSX easily in existing MVC projects.

-1

In your View, instead of using @Scripts.Render("~/Scripts/ReactJS/test.jsx")

you can try like this <script src="@Url.Content("~/Scripts/ReactJS/test.jsx")"></script> to create the referenced JavaScript file (test.jsx).

Shashwat Prakash
  • 434
  • 5
  • 14