Ract FontAwesome ES6 usage - reactjs

Good day
I am a novice React developer building a site for a client using ES6 standards. I have found a component for which the usage as description uses an older syntax, and I am having some trouble implementing my code. I am receiving an error message that I am not sue how to resolve.
The component in questions can be seen here:
https://www.npmjs.com/package/react-fontawesome
it instructs you to use the component as follows:
var React = require('react');
var FontAwesome = require('react-fontawesome');
React.render(<FontAwesome name='rocket' />, document.body);
To my understanding, this is an older way of writing React code. I have thus updated my code to for the ES6 standard.
I scratched in my package.json file to find out where to import the component from, so I am not sure if this is perhaps where I have gone wrong.
Below is a copy of my code using what I believe to be the correct implementation:
import React, { Component } from "react";
import FontAwesome from '#fortawesome/fontawesome-svg-core';
export class Footer extends Component {
constructor(props) {
super(props);
}
render = _ => {
return (
<div>
<FontAwesome name='rocket' />
</div>
);
}
}
When I import the component and run the code I get the following error:
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, or you might have mixed up default and named
imports.
Check the render method of Footer.
in Footer (created by App)
in div (created by App)
If anyone would be kind enough to let me know where I might be going wring, I would be incredibly grateful.

There's a simple example on their docs page that should help out:
import ReactDOM from 'react-dom'
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome'
import { faCoffee } from '#fortawesome/free-solid-svg-icons'
const element = <FontAwesomeIcon icon={faCoffee} />
ReactDOM.render(element, document.body)

Related

'Component exception' React Native

I copied my code from an old project of mine so it should be able to work. However, I think when I made the new project it accidentally updated the versions causing it to go thorough an error. This is my code:
import React, {useState} from 'react';
import { Text, View } from 'react-native';
import * as Font from 'expo-font';
import { AppLoading} from 'expo-app-loading';
import {enableScreens} from 'react-native-screens'
//import from libraries
import TabNavigation from './Navigation';
//import TabNavigation
enableScreens();
const fetchFonts = () => {
return Font.loadAsync({
'open-sans': require('./assets/fonts/OpenSans-Regular.ttf'),
'open-sans-bold' : require('./assets/fonts/OpenSans-Bold.ttf')
});
//fetch fonts from the folder so that we can style the title
};
export default function App() {
const[fontLoaded, setFontLoaded] = useState(false);
if(!fontLoaded){
return (
<AppLoading
startAsync ={fetchFonts}
onFinish={()=> setFontLoaded(true)}
/>
);
}
//this will ensure that the font will always be loaded.
return(
<TabNavigation />
);
}
The thing I'm trying to do is run this program and then return Navigation where all the navigation process works.
Here is the error:
Component exception
Element type is invalid: expected a string(for built-in components) or a class/function (for complete components) but got: undefined. You likely forgot to export your component from. the file it's defined in, or you might have mixed up a default and named imports. Check the render method of 'App'.
You don't need to do this fetchFonts method
to load the fonts. If you installed the fonts correctly you just need to put the attribute fontFamily in any style, with the name of the font as its value, for example: textStyle:{ fontFamily: 'Montserrat-Bold' }
For a better understanding you can check this link.
Change your import for app Loading
import AppLoading from 'expo-app-loading';
First, open the terminal and go to the project directory.
Second, run the following command to install the expo-app-loading module:
expo-app-loading
Third, import the module into your App.js file:
import AppLoading from 'expo-app-loading';
Tested on Expo 4.9.0

React Error: Error: Element type is invalid

Earlier today, I tried running create-react-app, but I got an error about templates and how my version of React may be out of date. So I removed React globally and then reinstalled. I ran create-react-app again and it started working again.
I was trying to create an app afterwards but I keep getting the following message:
×
Error:
Element type is invalid: expected a string (for built-in
components) or a class/function (for composite components) but got:
object. 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.
I never got this message before while using React. Here is my code so far:
App.js
import React, { Component } from 'react';
import UserOutput from './Components/UserOutput';
import UserInput from './Components/UserInput'
class App extends Component {
render() {
return (
<div>
<UserInput />
<UserOutput username="Test" />
</div>
)
}
};
export default App;
UserOutput.js
import React from 'react';
function UserOutput(props) {
return <h1>this is my username: {props.username} </h1>;
}
export default UserOutput;
UserInput.js
import React from 'react';
function UserInput() {
return <input>Name</input>
};
export default UserInput;
I tried searching for a fix for my error, but could not find a solution. I believe I am importing everything correctly and it complies without error in my IDE, but I get the error in my browser.

Invariant Violation: Error while using React-Dom renderToString() in es6 importing

This question is quite different as I searched a lot for similar but didnt find any I am creating a project of react server side rendering feature and using webpack to write the es6 code and babel to compile the jsx . In my express route I want to convert the App component to string and then want to pass to the static html part . it is working fine when I am doing like this
var App = renderToString(<h1> Working Fine now </h1>);
but now when I want the App component to be here its not working
var App = renderToString(<App />); // Not working
I am importing App component in express server like this
import React from "react";
import ReactDOMServer , {renderToString} from "react-dom/server";
import App from '../common/component/App.js';
My App.js
import React from "react"
export default class App extends React.Component{
render(){
return (
<div>
<h1>From COmponent</h1>
</div>
)
}
}
error
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
I checked some issues in Github too but there they were recommending to move to react-0.14 as those issues were old but now I am using react 16
Because you are already importing App at Line No 3
import App from '../common/component/App.js';
So, to fix your issues just replace this line
var App = renderToString(<App />); // Not working
with this
let MyApp = renderToString(<App />); // Working

Rearranging File Structure Throwing "Element type is invalid" Error

I'm reorganizing the code in my application into a bunch of sub-folders. I'm moving a top-nav component into a subfolder called navigation, this component makes up part of a 'main-nav' container. However, when I shift top-nav into the new folder I start getting the following erro
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 TopNavTemplate.
I've been reading through a lot of threads and I can't figure out why shifting the poisition would cause this. I've made sure that the component is pointing to the appropriate imports within the file restructure (these errors get thrown before the current error anyway, so it at least thinks that it's pulling everything in correctly.) I also don't think it's a syntax error in the import statement - I'm connecting the top-nav to my redux store as a default export, and I'm not importing it between {}.
Code for the top-nav export can be found below:
import React from 'react';
import {Link} from 'react-router-dom';
import ClickOutside from 'react-click-outside';
import {IconSprite} from '../general/icons.js';
import {Modal} from './modal.js';
import {HeaderSelect} from './select.js';
//Import statements that connect TopNav to the redux store
import * as actionCreators from '../../actions/actionCreator.js';
import { bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import logo from '../../logo.svg';
export class TopNavTemplate extends React.Component {
//Render function and a bunch of code goes here
}
function mapStateToProps(state) {
return {
selectedTarget: state.selectedTarget,
availableTargets: state.availableTargets,
modal: state.modal,
currentUser: state.currentUser,
isLoggedIn: state.isLoggedIn
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(actionCreators, dispatch);
}
const TopNav = connect(mapStateToProps, mapDispatchToProps)(TopNavTemplate);
export default TopNav;
I then import the TopNav into my main-nav layout like so:
import React from 'react';
import TopNav from '../components/navigation/top-nav.js';
import {SideNav} from '../components/side-nav.js';
export class MainNav extends React.Component{
render(){
return ([
<TopNav />,
<SideNav />
])
}
}
If I change the import statement to pull from the old version of the file
import TopNav from ../components/top-nav.js
everything works like a charm. I've even tried removing that file to prevent any kind of web-pack confusion but that doesn't seem to the issue. For some reason, moving this file into a different folder is now causing the export to be undefined instead of a proper react component? Feeling very lost.
It turned out to be a very stupid mistake - I'd forgotten to save one of the files I was importing while shifting everything around. For some reason this wasn't throwing an error that the import couldn't be found, and was instead causing the wrapped connect component to return as undefined.

Element type is invalid: expected a string (for built-in components) or a class/function

import React from 'react';
import ReactDOM from 'react-dom';
import Map from './components/map/container/map';
import App from './App';
import './index.css';
import shell from './shared/utility/shell';
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware, compose } from 'redux'
import { routerMiddleware, ConnectedRouter } from 'react-router-redux'
import thunk from 'redux-thunk'
import createHistory from 'history/createBrowserHistory'
import rootReducer from './reducers'
import registerServiceWorker from './registerServiceWorker';
import { Routes } from './config';
const history = createHistory();
const target = document.querySelector('#root')
const initialState = {};
const enhancers = [];
const middleware = [
thunk,
routerMiddleware(history)
];
if (process.env.NODE_ENV === 'development') {
const devToolsExtension = window.devToolsExtension;
if (typeof devToolsExtension === 'function') {
enhancers.push(devToolsExtension());
}
}
const composedEnhancers = compose(
applyMiddleware(...middleware),
...enhancers
);
const store = createStore(
rootReducer,
initialState,
composedEnhancers
);
render(
<Provider store={store}>
<ConnectedRouter history={history}>
<div>
<Routes />
</div>
</ConnectedRouter>
</Provider>,
target
)
registerServiceWorker();
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
I am trying to call an API from with the help of redux and display its data in a table. I am getting this error. Above is my index.js file.
1.
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.
2.
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.
I have referred to many answers I am not able to recognize the error.
Problem is in the import statements. You have not used curly braces while importing some components like createHistory.
If a component uses a default export like:
export default X
Then you can simply import it like:
import X from './X';
But if you are using a named export like:
export const X=1;
Then you need to import it in curly braces like:
import {X} from './X';
So have a look at your imports. This will resolve your issue.
I ran into the same problem in my react application. It's definitely your import statements as stated above.
I changed:
import {x} from '/x.js' to import x from '/x.js'
and that got the job done
I've also run into this error when one of the nested components attempted to render a component that did not exist. Specifically, I attempted to use
<Button ... />
a react-native component in React, where I should have been using
<button ... />
It can also be caused from where the entry point is.
In my case, the App.js was calling index.js (where the developer console was identifying the error, and where my RenderDom call was).
However, App.js was referencing a component, and it was within that component that I had the error (a reference to yet another component that did not exist).
For me, I faced this issue when I forget to use react-redux's connect in my export.
So,
changing:
export default(mapStateToProps, mapDispatchToProps)(ContentTile);
To:
export default connect(mapStateToProps, mapDispatchToProps)(ContentTile);
solved the issue. Really silly mistake
There are several reasons why this error might occur.
It is definitely related directly to an issue with one of your imports. This could be:
A missing/miss-imported module from a npm package.
A component missing the export or an altogether empty component
attempting to be imported.
mixed up named/default export/import
Check you aren't importing your component name in braces like this:
import {SomeComponent} from '../path/to/SomeComponent'; // nope
I realised I had done that and so I changed it to this and it started working:
import SomeComponent from '../path/to/SomeComponent'; // yes
I believe the {} are for selecting from imports with multiple exports like the React components etc, and without you get what the export default is, but maybe someone can comment to confirm that.
To add to previous replies, you also get this error if one of the components within the component you are trying to import is empty / does not have a correct render method.
As was sayed above, this issue with import. In my case it's was a CSSTransitionGroup import. After npm update the package 'react-transition-group' no longer contains CSSTransitionGroup, but it's contains different exports, like CSSTransition and TransitionGroup. So i just replace line:
import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup';
with
import TransitionGroup from 'react-transition-group/TransitionGroup';
In my case I solved it changing the components: They were written in functions declarations and I change them by classical Class declarations (class App extends React.Component instead of function App() )
I also had the similar problem while attempting to add routes into my application.
I then realised that i was importing { BrowserRouter, Route } from "react-router"; instead of correctly importing it from react-router-dom as below
import { BrowserRouter, Route } from "react-router-dom".
Thanks to the online community
Make sure you export the component. And if you are already exporting, then you might have missed the default.
export default function App(){
...
}
It's a special case, but Recharts threw this error for me when I attempted to put two charts inside one ResponsiveContainer. That is not supported.
You may also get this error if a sub-component of the component that the error references has not exported its function/class:
So the problem isn't in the referenced component but in a component that it is importing (which is not referenced in the error text).
Took me a while to find this bugger.
Sometimes, It could be as a result of importing from the wrong library, like in my experience, where I should have imported Input component from react native elements.
import { View, ActivityIndicator, Input } from 'react-native';
import { Input, Button } from 'react-native-elements';
In my case I resolved the problem by removing undefined component.
I imported that component from wrong module.
My problem is solved, the problem was instead of using
import { NavLink } from 'react-router-dom'
I used
import { NavLink } from 'react-dom'
I want to say this, coding includes paying attention to details.
I got this error just because import "FlatList" as "Flatlist" in react native expo project. And I spend one and a half hour to realize that :(
for me i was trying to route in app.js some component that have problem, so index.js will not render the / because of that in-proper import in app.js
so alwasy make sure components in app.js are working properly

Resources