ReactJS - Can't import component
Asked Answered
P

3

10

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?

Portuguese answered 4/11, 2015 at 13:58 Comment(0)
S
14

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.

Smith answered 4/11, 2015 at 14:1 Comment(3)
the second one was what i was searching for, thank you also for the link!Portuguese
You're right man, I've read the React docs and they explain the same recommendation. I'll follow this approach, thank you again!Portuguese
Why you use export default? Can I write two classes in one file and then call each of them in another file?Troublemaker
R
0

Make sure to include semicolons after the import statements too. you might get away with a browser (or environment like Node) reading the code in some cases, but the import function runs right into your export in this code.

Radiometer answered 10/9, 2019 at 14:14 Comment(0)
G
0

.js should have the first letter capital. Else import will not take place.

Galvano answered 6/11, 2022 at 14:22 Comment(2)
File names are case sensitive, but that doesn't mean they need the capital.Cota
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Chrisse

© 2022 - 2024 — McMap. All rights reserved.