Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing components in separate .JSX file

Tags:

.net

reactjs

I'm am using some ReactJS components for my views in a .Net MVC application.

Currently I have a single file containing all my components at: /scripts/react-app/MyApp.jsx

I'd like to split this into multiple files but when I move components into another file I get a run-time exception:

Uncaught ReferenceError: SomeComponent is not defined

How can I tell MyApp.jsx to reference another .jsx file?

EDIT:

I've tried bundling as suggested but I'm still getting the same error. Here's what I've done:

Added the below to BundleConfig.cs:

 bundles.Add(new JsxBundle("~/bundles/main").Include(
         "~/React/FileOne.jsx",
         "~/React/FileTwo.jsx",
         "~/React/FileThree.jsx"));

And in my _Layout.cshtml I've added: @Scripts.Render("~/bundles/main")

I'm trying to use a component defined in FileThree.jsx in FileOne.jsx but still getting the component is not defined error.

SECOND EDIT:

I changed to use Html helper in view and it started working for me:

@{
    ViewBag.Title = "Testing";
}

<div id="someContent">
    @Html.React("FileOneComponent", new
        {
            prop1 = "a",
            prop2 = "b",
        })
</div>

<script src="https://unpkg.com/[email protected]/dist/react.js"></script>
@Scripts.Render("~/bundles/main")
@Html.ReactInitJavaScript()
like image 952
RagtimeWilly Avatar asked Jun 10 '15 05:06

RagtimeWilly


People also ask

Should each React component be a separate file?

All components should be inside components directoryKeep each component in a separate file. If you need to have styles etc. for the component then create a folder for the component.

Is there a difference between adding JSX inside .JS and .JSX files?

They're completely interchangeable! In some cases users/developers might also choose JSX over JS, because of code highlighting, but the most of the newer editors are also viewing the react syntax correctly in JS files.

Can we use JS and JSX together?

JSX isn't necessary to use as React can be written with both JS and JSX, but JSX makes it easier for users to make React applications, as it is similar to HTML. It makes it easier to write and update HTML code, thus functionality is easier to handle.


1 Answers

To require a component first export it (in its own file), for example:

export default MyComponent;

In the file you want to use it you require it as follows:

import MyComponent from './mycomponent';

Be sure to specify the path correctly, in my example it assumes the same folder.

If you're having any bundling problems I'd heartily recommend create-react-app

This sets you up with a working dev environment, including tests.

like image 181
Mark Williams Avatar answered Oct 13 '22 14:10

Mark Williams