Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - Can't import component

I'm brand new to ReactJS. I'm developing a little single page app and I'm just trying to create my components to import within my main component.

TestComponent.jsx

import React from 'react'

export class TestComponent extends React.Component {

    render() {
        return (
            <div className="content">Test Component</div>
        )
    }
}

Inside my main.jsx I've imported this component calling

import TestComponent from './components/TestComponent.jsx'

Then I've tried to call my component for a specific route:

render(
    (<Router history={history}>
        <Route path="/" component={NavMenu}>
            <IndexRoute component={Index}/>
            <Route path="test" component={TestComponent}></Route>
        </Route>
    </Router>),
    document.getElementById('main')
)

I've not got any errors from the console, but I don't see my component. What am I doing wrong?

like image 597
Luca Mormile Avatar asked Nov 04 '15 13:11

Luca Mormile


People also ask

How import module react JS?

In React we use the keyword import and from to import a particular module or a named parameter. Let us now see the different ways we can use the import operation in React. Importing default export: Every module is said to have at most one default export.

Do I need to import React in every component?

You no longer need to import React from "react" . Starting from the release 17 of React, JSX is automatically transformed without using React. createElement . However, other exports like hooks must be imported.


1 Answers

The import syntax without curly braces is for importing default exports, not for importing named exports.

Make your component the default export:

TestComponent.jsx

import React from 'react'

export default class TestComponent extends React.Component {

    render() {
        return (
            <div className="content">Test Component</div>
        )
    }
}

Alternatively you should be able to import it as it is with the following import statement:

import { TestComponent } from './components/TestComponent.jsx'

You might want to read up on ES6 modules (e.g. in Exploring ES6) if you want to use ES6 in your React code.

like image 113
Mad Scientist Avatar answered Oct 20 '22 16:10

Mad Scientist