Export/import files .jsx in React - reactjs

i recently tried to make separate files .jsx in React. I made couple of them with export default name / import name from ./name.jsx'. But there comes problem. First i had imported Route and Links from react-router and console said it can't find Links, i found on stackoverflow to change it to react-router-dom, so i did it, and now console says i forgot to export some components. I can't find solution :( Could anyone help me ?
Here's my project :
https://github.com/tafarian/Portfolio
import React from 'react';
import ReactDOM from 'react-dom';
import './../css/style.scss';
import {
Router,
Route,
Link,
IndexLink,
IndexRoute,
hashHistory
} from 'react-router-dom';
import Template from './Template.jsx'
import Projects from './Projects.jsx'
import Home from './Home.jsx'
import AboutMe from './AboutMe.jsx'
import Contact from './Contact.jsx'

Such error as
"Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of App.
means that you are trying to create an undefined component, and as it said in error - usually this happens when you forget to export component or the component that you are importing does not exist.
When there is a lot of components and it's hard to find which one is "bad" I place a breakpoint at console.error(message); in React code and go up the stacktrace to the function createElement and it's arguments. Usually it helps me to identify the problem.
The main problem, is that your code is not compatible with react-router#4.
In this version you can not pass children and component to Route at the same time.
Also, there is no such a thing as IndexRoute and you should use BrowserRouter instead of Router, or you should pass an history object.
Take a look at the documention: https://reacttraining.com/react-router/web/guides/philosophy
And here is fixed version of yout app.jsx:
import React from 'react';
import ReactDOM from 'react-dom';
import './../css/style.scss';
import {
BrowserRouter,
Route,
Link,
hashHistory
} from 'react-router-dom';
import Template from './Template.jsx'
import Projects from './Projects.jsx'
import Home from './Home.jsx'
import AboutMe from './AboutMe.jsx'
import Contact from './Contact.jsx'
document.addEventListener('DOMContentLoaded', function(){
class App extends React.Component {
state = {
loading: true,
};
componentDidMount() {
setTimeout(() =>
this.setState({
loading: false
}), 2500);
}
render() {
if(this.state.loading === true) {
return (
<div id="preloader">
<div id="loader"></div>
</div>
)
}
return(
<BrowserRouter history={hashHistory}>
<Template>
<Route exact path="/" component={Home} />
<Route path='/aboutme' component={AboutMe} />
<Route path='/projects' component={Projects} />
<Route path='/contact' component={Contact} />
</Template>
</BrowserRouter>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
});

Related

How to resolve an error at reactDOM.render

index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "/src/App.jsx";
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<>
<BrowserRouter>
<App />
</BrowserRouter>
</>,
document.getElementById("root")
);
App.jsx
import React from "react";
import { Switch, Route } from "react-router-dom";
import Home from "/src/Home.jsx";
function App() {
return (
<>
<Switch>
<Route exact path="/" component={Home} />
</Switch>
</>
);
}
export default App;
Here is the codesandbox:
https://codesandbox.io/s/webapp-3tw58
Getting an error, not understanding how to resolve it
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of App.
You've done some mistake over there, regarding import and all that.
First thing is you can't import with file extension.
import App from "/src/App.jsx";
instead
import App from "/src/App";
and same for App.jsx file as well.
import Home from "/src/Home";
OR
I'll suggest to use the relative import,
import App from "./App";
Maybe this is causing the actual issue.
Updated:
By looking into your codesandbox, you're using the react-router-dom#v6 and there is a different way of using the Route. Please read it from here.
As mentioned by #Pradip Dhakal, this is likely an issue caused by react-router-dom version mismatch. Updating route definition as per new documentation seems to solve the issue:
App.jsx
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Home from "./Home";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
</Routes>
</BrowserRouter>
);
}
export default App;
Home.jsx
import React from "react";
function Home() {
return <div>Home</div>;
}
export default Home;

Render function is not called

I am trying to get my react component to render in Meteor. I don't see any error messages or anything in the console, however, the component doesn't seem to display.
I am using react-router. I added log statements and it appears that the renderRoutes() function does get called, also, I see errors in the console when I change the directories for my imports (I get an error if I change the first import statement to import {Home} from '../home/blah'). I am not really sure what to try next.
Here is my router, which is in client/imports/lib/router.js.
import React from 'react';
import { Router, Route, Switch } from 'react-router';
import {createBrowserHistory} from 'history';
import {Home} from '../home/home';
import {Login} from '../login/login';
import {Connect} from '../connect/connect';
const browserHistory = createBrowserHistory();
export const renderRoutes = () => (
<Router history={browserHistory}>
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/login" component={Login}/>
<Route exact path="/connect" component={Connect}/>
</Switch>
</Router>
);
Here is my home page. The other pages have a similar structure. The home page is in client/imports/home/home.js.
import React, { Component } from 'react';
export default class Home extends Component {
constructor(){
super()
this.state = {
}
}
render() {
return (
<div><h1>hello from the home page</h1></div>
);
}
}
Finally, this is my main.js. It's in client/main.js.
import { Meteor } from 'meteor/meteor';
import { render } from 'react-dom';
import { renderRoutes } from './imports/lib/router.js';
import './main.html';
Meteor.startup(() => {
render(renderRoutes(), document.getElementById('app'));
});
Again, I don't see any error messages. The home page just doesn't render. I put console.log's in the constructor for the Home component and I do not see anything. I'm not sure if there is something about React that I am not understanding or if I need to change the way I am using the router.
Please let me know what I should try next, and if there is any more information I should include.
Thanks!
If you're exporting component using export default
export default class Home extends Component {
then you should import it this way:
import Home from '../home/home';
Read more about named and default exports
For the future - back to the source, check original code (from docs) first (usually working) - it's not hard to see the difference ;)

Rendering React component in Redux application with React-Router v4

This is my first crack at trying to integrate React-Router4 into a React/Redux app. I've been stuck on the first hurdle for a couple hours as I'm reading the docs and a (very good) CSS-Tricks article.
The issue is that the won't render the 'Whatever' value I input at the component prop, which should be a component.
I've actually read almost entirely thru the (excellent) docs, beginning here: https://reacttraining.com/react-router/web/guides/quick-start
And I've consulted this article: https://css-tricks.com/react-router-4/
Which also includes this Codepen (to see if I did something obvious/stupid): https://codepen.io/bradwestfall/project/editor/XWNWge?preview_height=50&open_file=src/app.js
I'm just hoping someone on SO might be able to nudge me over this hump. I was expecting to at least be able to render this very simply without any additional libraries or adjustment to my stores based on: https://reacttraining.com/react-router/web/guides/redux-integration
entry point, index.js:
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import store from './stores'
import { Provider } from 'react-redux'
import Home from './components/Home'
import TopStories from './components/TopStories'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
// app entry point
const app = (
<Provider store={store.configure(null)}>
<Router>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/topstories" component={TopStories} />
</Switch>
</Router>
</Provider>
)
// virtual DOM render
ReactDOM.render(app, document.getElementById('root'))
TopStories.js component (renders ok in the '/' path if I switch it w/ Home)
import React, { Component } from 'react'
export default (props) => {
return(
<div>Top Stories component </div>
)
}
I was attempting to test by typing the path into the browswer.... Duh. I just needed to set up a quick link component and everything worked fine.

react-router-dom v4 | Context Router and Route Undefined

I'm running react-router-dom 4.1.1, I followed multiple React Router guides, even doing the react-router-tutorial which worked on my computer (though it was using react-router v2 or something similar). When I attempt to use react-router-dom v4 on a simple application, I run into many errors.
Scroll Down for Current Code & Error
//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory'
import App from './components/App';
import About from './components/pages/about';
const customHistory = createBrowserHistory()
ReactDOM.render((
<Router history={customHistory}>
<Switch>
<Route path='/' component={App} />
<Route path='/about' component={About}/>
</Switch>
</Router>
), document.getElementById('root'))
This code alone works and renders my 'App' component
But when I try to add a 'Link' component in my App component, it won't recognize it.
//App.js
import React from 'react';
import Header from './Header';
import { Link } from 'react-router-dom'
class App extends React.Component {
render() {
return (
<div className="App">
<Header className="Header" header="Header" />
<main className='main'>
<Link to='about'>About</Link>
</main>
</div>
);
}
}
export default App;
If I run this, I get the error:
TypeError: Cannot read property 'history' of undefined
at Link.render (/Users/Ryan/Desktop/df/grnd/node_modules/react-router-dom/Link.js:76:35)
at /Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactCompositeComponent.js:795:21
at measureLifeCyclePerf (/Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactCompositeComponent.js:75:12)
at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext
(/Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactCompositeComponent.js:794:25)
at ReactCompositeComponentWrapper._renderValidatedComponent (/Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactCompositeComponent.js:821:32)
at ReactCompositeComponentWrapper.performInitialMount (/Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactCompositeComponent.js:361:30)
at ReactCompositeComponentWrapper.mountComponent (/Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactCompositeComponent.js:257:21)
at Object.mountComponent (/Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactReconciler.js:45:35)
at ReactDOMComponent.mountChildren (/Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactMultiChild.js:236:44)
at ReactDOMComponent._createContentMarkup (/Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactDOMComponent.js:659:32)
If I comment out the 'Link' component in App.js, the program runs and loads 'App' from index.js.
This is only one error I've received out of many as I try to figure out why I can't run it. I have also received errors in which it says 'Route' is undefined or that 'Router' can't have nested children and so on. I find this problem to be at it's simplest.
The history I used for this example was taken from the example given on:
https://reacttraining.com/react-router/web/api/Router/history-object
First of all, you use a BrowserRouter, this one creates its own history object and uses this one. Therefore in your case you shouldn't be passing a history object to it. Actually it should even print a warning in your console after I looked at the code of BrowserRouter. And if I were you I'd keep it named as BrowserRouter, it makes it less error prone and clearer when you read the code.
Then, in v4, the Router can only have 1 child. But in the case of the Switch, it actually mounts only the matching route. I'm not sure if it's intended to be like this, try to change your hierchy to something different, and have the child of Router to always be mounted. Here would be an example taking your code :
//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import App from './components/App';
ReactDOM.render((
<BrowserRouter>
<App />
</BrowserRouter>
), document.getElementById('root'));
And then in your App you build your routing logic, that even makes more sense, since your App is probably the application, therefore it should always be present.
//App.js
import React from 'react';
import Header from './Header';
class App extends React.Component {
render() {
return (
<div className="App">
<Header className="Header" header="Header" />
<Switch>
<Route exact path='/' component={Home} />
<Route path='/about' component={About}/>
</Switch>
</div>
);
}
}
And your links would probably be inside the Header I suppose, or you may want to build a special Nav component for this, that may be included in the Header or some place else. Let's do it in the Header for now and see how that would work:
//Header.js
import React from 'react';
import {Link} from 'react-router-dom';
class Header extends React.Component {
render() {
return (
<header className="header">
<Link to='/'>Home</Link>
<Link to='/about'>About</Link>
</header >
);
}
}
Current Code
//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './components/App';
ReactDOM.render((
<BrowserRouter>
<App/>
</BrowserRouter>
), document.getElementById('root'))
//App.js
import React from 'react';
import Header from './Header';
import Main from './Main';
class App extends React.Component {
render() {
return (
<div className="App">
<Header className="Header" header="Header" />
<Main className="Main" />
</div>
);
}
}
export default App;
//Main.js
import React from 'react';
import { Switch, Route } from 'react-router-dom'
import Home from './Home';
import About from './About';
class Main extends React.Component {
render() {
return (
<div className='Main-Container'>
<Switch>
<Route exact path='/' component={Home} />
<Route path='/about' component={About} />
</Switch>
</div>
)
}
}
export default Main;
Most Recent Error
Warning: Failed context type: The context router is marked as
required in Switch, but its value is undefined.
in Switch (created by Main)
in div (created by Main)
in Main (created by App)
in div (created by App)
in App TypeError: Cannot read property 'route' of undefined
at Switch.render (/Users/Ryan/Desktop/df/grnd/node_modules/react-router/Switch.js:48:36)
at /Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactCompositeComponent.js:795:21
at measureLifeCyclePerf (/Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactCompositeComponent.js:75:12)
at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext
(/Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactCompositeComponent.js:794:25)
at ReactCompositeComponentWrapper._renderValidatedComponent (/Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactCompositeComponent.js:821:32)
at ReactCompositeComponentWrapper.performInitialMount (/Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactCompositeComponent.js:361:30)
at ReactCompositeComponentWrapper.mountComponent (/Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactCompositeComponent.js:257:21)
at Object.mountComponent (/Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactReconciler.js:45:35)
at ReactDOMComponent.mountChildren (/Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactMultiChild.js:236:44)
at ReactDOMComponent._createContentMarkup (/Users/Ryan/Desktop/df/grnd/node_modules/react-dom/lib/ReactDOMComponent.js:659:32)
I found out what's causing the error: Server Rendering
Currently, I am using this piece of code
//server.js
server.get('/', (req, res) => {
res.render('index', {
content: ReactDOMServer.renderToString(<App />)
});
});
Which renders to my ejs template
//index.ejs
<%- include('header') -%>
<div id="root"><%- content -%></div>
<%- include('footer') -%>
When I comment out content: ReactDOMServer.renderToString(<App />)and switch it to something like content: 'Hello' .... <Route/> and <Link/> work.

React router 3.0.2 + es6: React.createElement: type is invalid

While rewriting some components in es6 syntax my React router started throwing the following error:
Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of `Navicon`.
This error only springs if I include a <Link> component inside my Navicon component, which looks like this:
import React from 'react';
import Link from 'react-router';
import './navicon.css';
class Navicon extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div className='navicon-container' tabIndex='0'>
<div className={'dropdown'}>
<Link to={'/'}>Hello</Link>
</div>
</div>
)
}
}
export default Navicon;
The component that mounts my router looks like this:
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import App from './components/App';
import Home from './components/Home';
import About from './components/About';
import './main.css';
ReactDOM.render(
<Router history={browserHistory}>
<Route component={App}>
<Route path='/' component={Home} />
<Route path='/about' component={About} />
</Route>
</Router>,
document.getElementById('app')
);
I'm using "react-router": "^3.0.2"
Does anyone have any idea what might be tripping this error? This error never sprang when I was using React.createClass(), so I'm puzzled.
Ah, it seems that due to the export syntax on react router components, one evidently must use:
// import Link from react-router <- this doesn't work
import {Link} from react-router // <- this does
That little change resolves the error.

Resources