ReactJS - Can't import component - javascript

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?

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.

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.

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

Related

ReactJS Class Component Rendering Twice

Very simple example: My App.js file reads
import React from 'react';
import Test from './component/Test';
function App() {
return (
<div className="App">
<Test/>
</div>
)
}
export default App;
and my Test.js file reads
import React, { Component } from 'react'
class Test extends Component {
render() {
console.log('rendered')
return null
}
}
export default Test
In the console, 'rendered' is always printed twice. Why?
The reason is React.StrictMode.
React.StrictMode is a wrapper introduced in version 16.3.0 back in 2018 and in 16.8.0 it is applied also for hooks.
Code:
Check index.js for the below code
<React.StrictMode>
<App />
</React.StrictMode>
React.StrictMode
cannot spot side-effects at once, but it can help us find them by intentionally invoking twice some key functions.
These functions are:
Class component constructor, render, and shouldComponentUpdate methods
Class component static getDerivedStateFromProps method
Function component bodies
State updater functions (the first argument to setState)
Functions passed to useState, useMemo, or useReducer
Please check this blog
https://mariosfakiolas.com/blog/my-react-components-render-twice-and-drive-me-crazy/

React Component and render method are called twice

In my component Constructor and render method are called twice. I created a brand new project from create-react-app, it only one component other than App component so it is not so complex and complicated but still the problem persists.
import React from "react";
import logo from "./logo.svg";
import "./App.css";
import First from "./First";
function App() {
return (
<div className="App">
<First />
</div>
);
}
export default App;
import React, { Component } from "react";
class First extends Component {
static count = 0;
constructor(props) {
super(props);
this.state = {};
console.log("ctor");
alert("ctor");
}
render() {
First.count++;
console.log("Render method", First.count);
return <div>Hello World</div>;
}
}
export default First;
All other lifecycle hooks are being rendered once, no issues with them.
it's probably because of React StrictMode in your index.js file.
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
strict mode checks for potential problems and it caused to run some lifecycle methods (like constructor, render, componentShouldUpdate, etc) twice.
if it bugs you, you can simply remove it but better to don't.
Strict mode checks are run in development mode only; they do not impact the production build.
you can read more about it on strict-mode
your code is just fine Constructor and render method are called only once i have tried in my machine.

ES6+React, Error:React.createElement: type should not be null, undefined, boolean, or number

Learning ReactJS with ES6. Trying to implement React-Bootstrap components. I am also using the react router. I am trying to implement the Navbar component.
It will just be a nabber with the brand and a search box. I aim to expand and use the search box component a lot more so I have put it in its own separate component below.
LocationSearchBox.js
import React, {PropTypes} from 'react'
import Form, {FormGroup, FormControl} from 'react-bootstrap'
export default function LocationSearchBox(props) {
return (
<FormGroup>
<FormControl type="text" placeholder="Search" />
<Button bsStyle="success" type="submit">Submit</Button>
</FormGroup>
)
}
The navber will be on all pages so I have put it in the topmost route and its component is the Main.js file shown below along with routes.js to manage client side routes.
import React, {Component} from 'react';
import {Navbar, NavbarHeader, NavbarBrand, NavbarCollapse} from 'react-bootstrap';
import {default as Search} from './LocationSearchBox'
export default class Main extends Component{
constructor(props) {
super(props);
this.props = props;
}
render() {
return(
<Navbar>
<NavbarHeader>
<NavbarBrand>
React-Bootstrap
</NavbarBrand>
</NavbarHeader>
<NavbarCollapse>
<Search/>
</NavbarCollapse>
</Navbar>
)
}
}
routes.js
import React from 'react';
import ReactRouter, {Router, Route, IndexRoute, browserHistory} from 'react-router';
import Main from '../components/Main';
export var routes = (
<Router history={browserHistory}>
<Route path='/' component={Main} />
</Router>
);
Index.js is below and is the entry file to use in Webpack/babel
import React from 'react';
import ReactDOM from 'react-dom';
import {routes} from './config/routes';
ReactDOM.render(routes, document.getElementById('root'));
So when i run web pack-dev-server, go to localhost:8080 as the default port the main route should be hitting. I believe it does but I get errors, namely 3 of the same kind.
Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of `Main`.
I believe it might be due to the way I am importing the Navbar components in Main.js, such as NavbarHeader, NavbarCollapse etc but that is a guess. I would really appreciate any help in solving this issue, thank you.
You are using the Button component without importing it:
<Button bsStyle="success" type="submit">Submit</Button>
Import it correctly and the issue should be resolved.

parentheses around import ES6

I'm learning React Native, just curious about the parentheses in the first line of import
import React, { Component } from 'react';
import { AppRegistry, Text } from 'react-native';
class HelloWorldApp extends Component {
render() {
return (
<Text>Hello world</Text>
);
}
}
AppRegistry.registerComponent('HelloWorldApp', () => HelloWorldApp);
Why wrap Component with {} but not React?
React is the default export (there can only be one of these per module). Default exports can be imported like this:
import React from "react";
Component is a named export (there can be many of these). Named exports are imported like this:
import { Component } from "react";
What you're seeing is both of these things imported on the same line.
default exports aren't automatically available everywhere, so they still need importing.
Note that the reason React needs importing at all is because of the way that JSX is transformed into JS - React needs to be available so <Text> can be transformed into React.createElement(Text, ....
I think it's just a matter of shorting the next invocations, since Component is a subclass of React, so that way you use React as default with all it has in it. and Component as a single class you'd use. By the way you use braces in import when you want something specific as a method or class, that is named export. There's a better explanation in here.
Having both named exports and a default export in a module
import React from 'react';
import Navbar from 'react-bootstrap/lib/Navbar';
export default class MyNavbar extends React.Component {
render(){
return (
<Navbar className="navbar-dark" fluid>
...
</Navbar>
);
}
}

Warning: Failed propType: Invalid prop 'component' supplied to 'route'

When I run the my app on browser I get on my console:
"Warning: Failed propType: Invalid prop 'component' supplied to
'route'"
My routes file:
import { Route, IndexRoute } from 'react-router';
import React from 'react';
import App from './container/App';
import PContainer from './container/PContainer/PContainer';
import PView from './container/PView/PView';
const routes = (
<Route path="/" component={App} >
<IndexRoute component={PContainer} />
<Route path="/Posts View" component={PView} />
</Route>
);
export default routes;
My PView file:
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
class PView extends Component {
render() {
return (
<div>
<h1>List of Posts</h1>
</div>
);
}
}
export default connect()(PView);
Can anyone tell me why I am getting this error?
I met the same issue as you.
When I put a connect() component into <Route />, this warning must be there. If the component is not a connect() one, then the issue will not be there.
Solution
You can change the line
<Route path="/Posts View" component={PView} />
to
<Route path="/Posts View" render={(props) => <PView {...props} />} />
then the issue should go away.
Thinking
Look at the document of React-router
component should be used when you have an existing component (either a
React.Component or a stateless functional component) that you want to
render. render, which takes an inline function, should only be used
when you have to pass in-scope variables to the component you want to
render.
So when you would like to define a route of connect() component, you are implicitly going to pass some additional props into it, then according to the document you should use render instead of component. I guess this is the reason of warning happened.
Make sure that App, PContainer, and PView are all valid React components. Check module's imports and exports. Export should be with "default", otherwise you should use named import: import {somecomp} from './somecomp'. Check your routes to components.
Your routes look a bit weird: './container/PContainer/PContainer' and './container/PView/PView'.
Maybe it should be './container/PContainer' and './container/PView', if you don't have PContainer and PView folders.
Recently, I have been through this issue. I found that if you have any imported component which is empty or returning nothing then this issue arises because react could not consider it as a valid component.
Have a look if you have any component that you might have left empty.

Categories

Resources