How can I export a stateless pure dumb component?
If I use class this works:
import React, { Component } from 'react';
export default class Header extends Component {
render(){
return <pre>Header</pre>
}
}
However if I use a pure function I cannot get it to work.
import React, { Component } from 'react';
export default const Header = () => {
return <pre>Header</pre>
}
Am I missing something basic?
ES6 doesn't allow export default const. You must declare the constant first then export it:
const Header = () => {
return <pre>Header</pre>
};
export default Header;
This constraint exists to avoid writting export default a, b, c; that is forbidden: only one variable can be exported as default
Just as a side note. You could technically export default without declaring a variable first.
export default () => (
<pre>Header</pre>
)
you can do it in two ways
const ComponentA = props => {
return <div>{props.header}</div>;
};
export default ComponentA;
2)
export const ComponentA = props => {
return <div>{props.header}</div>;
};
if we use default to export then we import like this
import ComponentA from '../shared/componentA'
if we don't use default to export then we import like this
import { ComponentA } from '../shared/componentA'
You can also use a function declaration instead of assignment:
export default function Header() {
return <pre>Header</pre>
}
In your example, you already use curly brackets and return so this is apparently matching with your needs with no compromise.
Related
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;
I'm trying to export a component without the decorators (connect() in this case)
for unit testing with jest.
So, how could I do this:
import React, { Component } from 'react';
import { connect } from 'react-redux';
export class Header extends Component {
render(){
return <pre>Header</pre>
}
}
export default connect()(Header);
With this component (the export at the beginning doesn't work, it stills exports the connected component)
export let Header = props => {
render(){
return <pre>Header</pre>
}
}
Header = connect()(Header);
export default Header;
Use different variable for your connected component as the following code:
export let Header = props => {
render(){
return <pre>Header</pre>
}
}
let HeaderConnected = connect()(Header);
export default HeaderConnected;
Now you can import your Header freely without using connect()
This can be done without even changing default export:
export let Header = props => {
render(){
return <pre>Header</pre>
}
}
export default connect()(Header);
There may be no need to export original component for connect alone because most well-designed HOCs expose original component:
import Header from '...';
const OriginalHeader = Header.WrappedComponent;
Ho can I export both a class and a function from a react class.
Below is my class and I'm trying to export the onKeyHandler to unit test it. I tried just adding export before the onKeyHandler but my linter didn't like that. How would I go about exporting both one as a default and the other as a function to test.
import React, { Component } from 'react';
class MyComponent extends Component {
onKeyHandler = ({ target, keyCode }) => {
};
render() {
return (
<div>
sdfsdfds
</div>
);
}
}
export default MyComponent;
To export a function, it has to be outside the class. But you can test it without exporting.
Try this with sinon
// import
import 'sinon' from sinon.
// in your test case
let onKeySpy = sinon.spy(MyComponent, "onKeyHandler");
// logic goes here
expect(onKeySpy.called).toBeTrue();
I haven't tried this but this should work. You can spy in a similar way with jest.spyOn() as well.
If you need to stub the method, you can use prototype
let onKeyStub = sinon.stub(MyComponent.prototype, "onKeyHandler");
I was going through React Navigation docs and I encountered something like this over there:
import Ionicons from 'react-native-vector-icons/Ionicons';
import { createBottomTabNavigator } from 'react-navigation';
export default createBottomTabNavigator(
{
Now, I am unable to comprehend what this line does:
export default createBottomTabNavigator(
I mean it definitely exports something but is it a function?
If yes, then shouldn't it be like:
export default function createBottomTabNavigator(
or According to ES6 something like this:
export default function createBottomTabNavigator = () =>{
The code is equivalent to
const MyBottomTabNavigator = createBottomTabNavigator( { /* ... */ });
export default MyBottomTabNavigator;
The function is called, an Object is returned. The Object is exported and used elsewhere.
Edit:
More example code in the same vein:
const rootOf2 = Math.sqrt(2.0);
export default rootOf2;
Answer given by Chris G is correct. I would also like to add that there is the difference between two ways you can export your variables or functions, by export and export default.
Imagine having variable in file const myVar = 'someValue';
If you export it from file just with export export { myVar } you would have to import it in the file where you would like to use your variable of function like this: import { myVar } from 'name-of-your-module';
In other case, where you export it with default export default myVar, you can import it without {} - like this: import myVar from 'name-of-your-module'
Export default serves to export a single value or to have a fallback value for our module.
I'm trying to learn react-redux architecture, and I failed on the most basic stuff.
I created class HomePage and used react-redux connect() to connect it to store's state and dispatch.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {HomeButtonClickAction} from "./HomeActionReducer";
import {connect} from "react-redux";
class HomePage extends Component {
constructor(props) {
super(props);
console.log('HomePage props');
console.log(this.props);
this.buttonClicked = this.buttonClicked.bind(this);
}
buttonClicked() {
console.log('button cliked');
this.props.buttonClick();
}
render() {
console.log('Re-rendering...');
let toggleState = this.props.toggle ? 'ON' : 'OFF';
return (
<div>
<button onClick={this.buttonClicked}>{ toggleState }</button>
</div>
)
}
}
HomePage.propTypes = {
toggle: PropTypes.bool.isRequired,
onClick: PropTypes.func.isRequired
};
const mapStateToProps = (state, ownProps) => {
return {
toggle: state.toggle
}
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
buttonClick: () => {
dispatch(HomeButtonClickAction());
}
}
};
const HomeContainer = connect(
mapStateToProps,
mapDispatchToProps
)(HomePage);
export default HomePage;
But it's not working for me. HomeContainer doesn't pass props to HomePage component.
I've got these warnings in devtools.
My index.js looks like this.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import AppReducer from "./reducers/AppReducer";
import { createStore } from "redux";
import { Provider } from 'react-redux';
const store = createStore(AppReducer);
ReactDOM.render(
<Provider store={ store }>
<App/>
</Provider>,
document.getElementById('root')
);
registerServiceWorker();
and AppReducer.js
import { combineReducers } from 'redux';
import { toggle } from '../home/HomeActionReducer';
const AppReducer = combineReducers({
toggle
});
export default AppReducer;
and HomeActionReducer.js
const HOME_BUTTON_CLICK = 'HOME_BUTTON_CLICK';
export function toggle (state = true, action) {
console.log('toggle launched');
switch (action.type) {
case HOME_BUTTON_CLICK :
return !state;
default:
console.log('Toggle reducer default action');
return state;
}
}
export function HomeButtonClickAction() {
console.log('action emitted');
return {
type: HOME_BUTTON_CLICK
};
}
Being a newbie I'll really appreciate your help :)
You are exporting HomePage, which is the presentational component. You want to export HomeContainer, which is the container that passes the props to HomePage through connect.
So replace this
export default HomePage;
with this
export default HomeContainer;
You can also directly write
export default connect(mapStateToProps, mapDispatchToProps)(HomePage);
Note that, since it's the default export, you can name the import as you want, eg.:
import HomePage from './HomePage' // even if it's HomeContainer that is exported
You have this:
const HomeContainer = connect(
mapStateToProps,
mapDispatchToProps
)(HomePage);
export default HomePage;
To create an instance of the connect component you need to do this:
export default connect()(HomePage);
Notice I did not write export default twice, bad practice, you only export default once per component so the connect() goes inside that same line of code and the invocation or second set of parentheses you wrap around the component you are working in.
This connect() function is actually a React component that you are going to pass some configuration to and the way you begin to do that is by calling mapStateToProps like so:
const mapStateToProps = () => {
};
export default connect()(HomePage);
You could also do:
function mapStateToProps() {
}
If you read it, it makes sense, this is saying that we are going to map our state object, all the data inside the redux store and run some computation that will cause that data to show up as props inside our component, so thats the meaning of mapStateToProps.
Technically, we can call it anything we want, it does not have to be mapStateToProps, but by convention we usually call it mapStateToProps and its going to be called with all the state inside of the redux store.
const mapStateToProps = (state) => {
};
export default connect()(HomePage);
The state object contains whatever data you are trying to access from the redux store. You can verify this by console logging state inside the function like so:
const mapStateToProps = (state) => {
console.log(state);
return state;
};
export default connect()(HomePage);
I am returning state just to ensure that everything is working just fine.
After defining that function, you take it and pass it as the first argument to the connect() component like so:
const mapStateToProps = (state) => {
console.log(state);
return state;
};
export default connect(mapStateToProps)(HomePage);
Thats how we configure the connect component.We configure it by passing it a function. Run that and see what happens.