Why export default doesn't work in this simple code? - javascript

Why when I use export default on index.js module it says:
export 'appReducers' (imported as 'appReducers') was not found in './reducers/index' (possible exports: default), but when I change it to module.exports the error go away, why is that?
At redux.js
import { appReducers } from './reducers/index'
const Store = () => {
console.log(appReducers);
}
export default Store
in index.js
const appReducers = "hello world";
export default appReducers
in app.js
import React, { useState, useEffect, useMemo } from 'react';
import Store from './redux'
function App() {
Store();
return (
<div>
</div>
);
}
export default App;

The problem is in redux.js. Instead of
import { appReducers } from './reducers/index'
You need
import appReducers from './reducers/index'
What you were doing before was a named import, not a default import.

Related

React JS: How can I export different components based on environment variable?

React JS code:
I want the src/app.jsx to do export default App when the REACT_APP_AUTH_SERVER variable in .env does not exist or have other value, and do export default withAuthenticator(App) when the REACT_APP_AUTH_SERVER variable in .env does exist, and has value aws-cognito:
src/app.jsx:
import React, { Component } from 'react';
import SecuredGate from './SecuredGate/SecuredGate';
import { withAuthenticator } from '#aws-amplify/ui-react'
import './App.css';
import '../fontStyles.css';
class App extends Component {
render() {
return (
<div>
<SecuredGate />
</div>
);
}
}
const Result = () => {
if (process.env.REACT_APP_AUTH_SERVER && process.env.REACT_APP_AUTH_SERVER === "aws-cognito"){
return withAuthenticator(App);
}
return App;
}
// export default App;
// export default withAuthenticator(App)
export default Result;
However, this is not working.
If I do:
export default App;
// export default withAuthenticator(App)
, it works, and if I do:
// export default App;
export default withAuthenticator(App)
it works as well.
So what am I missing?
I think the problem is that the Result component returns a component instead of an element. To understand this better look at what App component does when called with <App />. It runs the code in its body and returns some markup. But what happens if you call <Result />. It will run the code in its block and return another component (a function). So to solve this you can try:
const Result = (process.env.REACT_APP_AUTH_SERVER && process.env.REACT_APP_AUTH_SERVER === "aws-cognito")
? withAuthenticator(App)
: App;
}
export default Result;

Ant-Design CSS not loading properly

I am having an issue with rendering my Ant-Design CSS on the first-render using React.js. I have a very basic page, that is just rendering a button.
import React from 'react';
import { Button } from 'antd';
const LoginPage = () => {
return (
<div>
<Button type="primary">Button</Button>
</div>
)
};
export default LoginPage;
I am trying to import the Ant-Design modules through the config-overrides.js file, as per the documentation:
const { override, fixBabelImports } = require('customize-cra');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: 'css',
}),
);
Here is my index.js file:
import { Provider } from 'react-redux';
import thunkMiddleware from 'redux-thunk';
import { createStore, applyMiddleware } from 'redux';
import 'normalize.css';
import App from './components/App/App';
import reducers from './reducers';
import { fetchUser } from './actions';
import * as serviceWorker from './serviceWorker';
const store = createStore(reducers, applyMiddleware(thunkMiddleware));
store.dispatch(fetchUser()).then(() => console.log(store.getState()));
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
serviceWorker.unregister();
And here is my App.js and App.css for more reference:
import React, { Component } from 'react';
import LoginPage from '../LoginPage/LoginPage';
import DashboardPage from '../DashboardPage/DashboardPage';
import { Spin } from 'antd';
import './App.css';
import { connect } from 'react-redux';
class App extends Component {
constructor(props){
super(props);
this.state = {
loggedIn: false
}
}
componentDidMount(){
this.setState({loggedIn: true });
}
render() {
return <LoginPage/>
}
}
const mapStateToProps = (state) => {
console.log(state);
return {
user: state.currUser
};
};
export default connect(mapStateToProps)(App);
#import '~antd/dist/antd.css';
However, on the first render it will only show a normal button, before fixing itself a second later. Here are two images that show the problem:
And here is the page after the second render:
Just import this file in your jsx file or js file:
If you import it in App.jsx file once then no need to import in other files
import "antd/dist/antd.css";
Add #import '~antd/dist/antd.css';
To the top of either/both of App.css and Index.css.
Hope that helps! đź‘Ť.
P.S - If you are using a single component for instance lets say Input, then import only that part.
import 'antd/es/input/style/index.css';
this below import is used my react project with create-react-app cli
import 'antd/dist/antd.css',
use this import to your root component.
Do NOT import the root styles from ant, as they contain some global styles, unfortunately, and will affect yours styling anyway, this was addressed a lot of times to them, but still I found the only solution is to directly import the components styling like this (replace select with your component):
import "antd/lib/select/style/index.css";
In your index.js file, you can import ant style files:
import 'antd/dist/antd.css';
As of this issue, please use the minified version.
import "antd/dist/antd.min.css";

TypeError: undefined is not an object (evaluating 'store.getState')

I'm following the Let’s Build: Cryptocurrency Native Mobile App With React Native + Redux tutorial.
When I create my store in App.js, the app works fine
import { createStore, applyMiddleware, compose } from 'redux';
import devTools from 'remote-redux-devtools';
import React, { Component } from 'react';
import { Platform, View } from 'react-native';
import { Provider } from 'react-redux';
import promise from 'redux-promise';
import thunk from 'redux-thunk';
import logger from 'redux-logger';
import { Header, CryptoContainer } from './src/components';
import rootReducer from './src/reducers';
const middleware = applyMiddleware(thunk, promise, logger);
const Store = createStore(rootReducer, compose(middleware, devTools({
name: Platform.OS,
hostname: 'localhost',
port: 5678
}), ));
export default class App extends Component {
render() {
return (
<Provider store={Store}>
<View>
<Header />
<CryptoContainer />
</View>
</Provider>
);
}
}
but when I move the store logic to a new file ./src/Store.js,
import { Platform } from 'react-native';
import { createStore, applyMiddleware, compose } from 'redux';
import devTools from 'remote-redux-devtools';
import promise from 'redux-promise';
import thunk from 'redux-thunk';
import logger from 'redux-logger';
import rootReducer from './reducers';
const middleware = applyMiddleware(thunk, promise, logger);
const Store = createStore(rootReducer,compose(middleware,devTools({
name: Platform.OS,
hostname: 'localhost',
port: 5678
}),
)
);
export default Store;
and use it in App.js like
import React, { Component } from 'react';
import { View } from 'react-native';
import { Provider } from 'react-redux';
import { Header, CryptoContainer } from './src/components';
import { Store } from './src/Store';
export default class App extends Component {
render() {
return (
<Provider store={Store}>
<View>
<Header />
<CryptoContainer />
</View>
</Provider>
);
}
}
I get
TypeError: undefined is not an object (evaluating 'store.getState')
What's causing my build (expo start) to fail when I import Store.js?
It seems the import statement is not right. It should be:
import Store from './src/Store';
if you're importing a single named export
e.g where you've done export const MyComponent = () => {} you'd import it like import { MyComponent } from "./MyComponent"
if you're importing a default export e.g where you've done const MyComponent = () => {} export default MyComponent you'd import it like import MyDefaultComponent from "./MyDefaultExport"
I got this error because I was exporting the wrong component from my main App file.
I was exporting this:
import React from 'react'
import { Provider } from 'react-redux'
import { createAppContainer } from 'react-navigation'
import Navigator from './src/components/Navigator'
import { store } from './src/store'
const App = createAppContainer(Navigator);
const Wrapped = props => (
<Provider store={store}>
<App />
</Provider>
)
export default Provider; // wrong!
That last line should be:
export default Wrapped; // right!
The answer from Itunu Adekoya shows that you can decide how you want to export / import, and in this case about personal preference, as there isn't a perf difference.
In the case where you have a lot of exports from a file, and perhaps some are unrelated or won't all be used together, it is better to export them individual as consts and then in other file only import what you need via import { } format, this will be sure to only include relevant imprts
in my case its casing & named import issue. imported as
import store from './Redux/Store'
it should be
import {Store} from './Redux/Store'

export default usage with deconstruct

I came to a codebase that did this
//index.js
export { default } from './Tabs'
export { default as Tab } from './Tab'
//Tab.js
export default class Tab extends Component {
render() => 'Something'
}
It's understandable that the author put Tab files under a Tab folder so that in other place he can just do import './Tabs' but why within the index.js he need to deconstruct?
Lots of people follow this nomenclature where the index file is just exports which then makes the imports easier.
It lets you import from the Tabs folder without explicitly saying the index.js filename. Most importantly it lets you import things from the folder Tab in just one statement.
For Example:
// Tab/Tab.js
import React, { Component } from "react";
class Tab extends Component {
render() {
return <span>Tab</span>;
}
}
export default Tab;
// Tab/Tabs.js
import React, { Component } from "react";
class Tabs extends Component {
render() {
return <span>Tabs</span>;
}
}
export default Tabs;
// Tab/index.js
export Tab from "./Tab";
export Tabs from "./Tabs";
// Main file
import React from "react";
import { render } from "react-dom";
import { Tab, Tabs } from "./Tab";
const App = () => (
<div>
<Tab />
<Tabs />
</div>
);
render(<App />, document.getElementById("root"));
demo: https://codesandbox.io/s/rr6klxj5j4
You can have a single default export from your file, Also writing
//index.js
export Tabs from './Tabs'
export Tab from './Tab'
will export them as a named export which you can later import as
import { Tabs, Tab } from './Tabs'
Also to understand the point default import is nothing different from an export named as default, so when you write
//index.js
export { default } from './Tabs' // Exports the Tabs as default
export { default as Tab } from './Tab' // imports the default from Tab and exports it as Tab
You could also write the above as
export { default } from './Tabs'
export Tab from './Tab'
In the above two cases you would import them as
import Tabs, { Tab } from './Tabs'
Check Error Exporting a component without importing for some more details

Prefer default export eslint error

I am getting this eslint error:
Prefer default export
import React, { Component } from 'react';
class HomePage extends Component {
render() {
return (
<div className="Section">HomePage</div>
);
}
}
export { HomePage };
I have tried doing:
export { default as Homepage };
and then I get a fatal parsing error.
Then I changed it to:
export default HomePage;
Which clears the eslint error.
But then throws:
'./HomePage' does not contain an export named 'HomePage'.
Because I am calling HomePage like this:
import { HomePage } from './HomePage';
If I remove the brackets then I get this error:
"export 'default' (imported as 'HomePage') was not found in
'./HomePage'
import HomePage from './HomePage';
<PrivateRoute exact path="/" component={HomePage} />
What would be the proper way of changing this to the preferred default export?
From eslint-plugin-import
When there is only a single export from a module, prefer using default export over named export.
class HomePage extends Component {
//....
}
export default HomePage
In another file :
import HomePage from './Hello';
Check here codesandbox
Here's an example using functions:
function HomePage() {
function aHelperMethod() {
//
}
return {
aHelperMethod,
}
}
Now to import it in another file
import HomePage from './Hello';
And to use it you'll have to instantiate it
const homePage = HomePage()
homePage.aHelperFunction()
In some cases there should be more than one named export in the module.
export const foo = 'foo';
export const bar = 'bar';

Categories