Search code examples
importexportreactjs.net

In ASP NET CORE 3.1 with ReactJS.NET how to reference components in multiple .JSX files


Right of the start: I have seen all the posts and have in last few days tryed all their permutations, but this does not seem to work for me.

My project is ASP NET Core 3.1. I have followed this tutorial: https://reactjs.net/tutorials/aspnetcore.html where all react react components are defined in a single file. I want for every component to be in it's own file. When I tryed to use multiple .jsx files with 'export default' and 'import from', my .jsx simply does not execute. == If all components are in the same file all works fine. But as soon as I add import A from './test.jsx' the code fails silently. It just does not get executed. No errors, exceptions...

Here is my project tree: enter image description here

Here are my script references in Index.html:

<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<link href="~/lib/bootstrap/dist/css/bootstrap.css" rel="stylesheet" />
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0      /umd/react.development.js"></script>
<script crossorigin src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/1.7.1/remarkable.min.js"></script>
<script src="~/Scripts/dist/Home/react/bundle.js"></script>

<script src="@Url.Content("~/js/test.jsx")"></script>
<script src="@Url.Content("~/js/MainPage.jsx")"></script>

Here is The MainPage.jsx file that works until I add import clause:

import Test from './test.jsx';

class MainPage extends React.Component {

render() {
    return (
        <div className="main">
            <h2>Main page stuff:</h2>
            <StatusBar />
            <Test />
        </div>
    );
}
} 

class StatusBar extends React.Component {

render() {
    return (
        <div className="status">
            <h4>Status Bar</h4>
        </div>
    );
}

}

And finaly here is the test.jsx:

export default class Test extends React.Component {
render() {
    return (
        <div className="test">
            <h4>Test Bar</h4>
        </div>
    );
}
}

Maybe I need another nuget?: enter image description here

Aldo I am quite fluent in .NET env, I am completely new to javascript and react so please explain in detail. In .NET we call this using a namespace or referencing a namespace.


Solution

  • Don't use import or require at all.

    Instead just reference ur react components files as a script in your root html file (where that react are rendered (<div id="root"></div>), index.html in your case.

    So in index.html, just add:

    <script src="@Url.Content("~/js/test.jsx")"></script>
    

    And that it.