I am still getting a hang of react+redux, and ES6. I am trying to implement socketio, and I come across the problem of having to export socketio connect with my redux's connect.
redux connect
export default connect(mapStateToProps, matchDispatchToProps)(UserList);
socketio connect
export default socketConnect(App);
Question
What is the correct syntax to make them work together?
You can't have more than one default export.
Instead, use named exports.
// moduleName.js
export const ConnectedUserList = connect(mapStateToProps, matchDispatchToProps)(UserList)
export const RealTimeApp = socketConnect(App);
Require the exports by name.
// otherModule.js
import { ConnectedUserList, RealTimeApp } from "./moduleName"
You can mix default export and named export.
export default ConnectedUserList = connect(mapStateToProps, matchDispatchToProps)(UserList)
export const RealTimeApp = socketConnect(App);
And after, you can import your exports :
import ConnectedUserList, { RealTimeApp } from "./moduleName"
One possibility I've not seen mentioned. You can have only one default export, but what you export can be an object with multiple members:
// MyModule.js
const componentA => () => {return <div>Component A</div>;}
const componentB => () => {return <div>Component B</div>;}
export default { componentA, componentB };
And then:
import MyModule from "./MyModule";
MyModule.componentA();
export default () => {
return {export1, export2};
}
export default { constOne, constTwo } and import data from './data.js' will do the trick. To access the data in the target file, it would be like so: {data.constOne} or {data.constTwo}
Example
Lets say we have the following data.js file:
const summary = [
{ label: 'Turned pro', content: '2020' },
{ label: 'Profession', content: 'Engineer' }
]
const reputation = [
{ community: 'Code Review', points: 176 },
{ community: 'Game Development', points: 101 }
]
export default { summary, reputation }
One way to import and use the data, would be like so:
import data from './data.js'
function App(){
return (
<div>
{data.summary.map((el) => <p>{el.label}</p> )}
</div>
)
}
Related
I have two components, one for API and another for UI. I am trying to access a function from API Component in UI component like below,
import APIComponent "./APIComponent";
APIComponent.getData().(response:any) => { //showing error here as "Property 'getData' does not exist on type '{ APIComponent: () => any; }'"
console.log(response);
})
Below is my APIComponent,
const APIComponent=():any=>{
const getData=():any =>{
//forming request
}
}
Thanks in Advance.
You should export them first, without an default export, so that would be
export const APIComponent=():any=>{}
export const getData=():any =>{}
Then try to import them
import {getData} "./APIComponent";
or try to export default and object and in that object add the functions as methods like so
export const APIComponent = () => {};
const getData = () => {
alert("Getting the data");
};
export default {
getData
};
Then you can actually export them and import them without the Destructure Syntax
import APIComponent from "./APIComponent"
APIComponent.getData();
Have a look at this Sandbox
https://codesandbox.io/s/morning-feather-9z24o?file=/src/App.js
I am trying to understand how to get the props to show up when exporting a functional component like this
export const functionName = ({...props}) => {
console.log(props); // undefined
return <p>Hello</p>
}
functionaName.propTypes = { // propTypes here }
const mapStateToProps = state => ({ // state stuff here })
const mapDispatchToProps = { // props mapping here }
export default connect(mapStateToProps, mapDispatchToProps)(functionName); // works like it should
The normal method works as it should
functionaName.propTypes = { // propTypes here }
const mapStateToProps = state => ({ // state stuff here })
const mapDispatchToProps = { // props mapping here }
export default connect(mapStateToProps, mapDispatchToProps)(functionName);
I am trying to organize my imports and have a folder structure like so
components
item // contains the component
index.jsx
index.js
index.js
export * from './item';
Then doing an import would be like this
import { functionName } from '../components';
My actual code does have a return value, I just truncated it for this post. Any ideas on how to accomplish what I am looking to achieve?
For this code to work:
import { functionName } from '../components';
You need your components/index.js too look like this:
import { someFunction } from './item';
export someFunction;
// Or one liner:
export { someFunction } from './item';
Here are some examples from one of my projects:
export { default as AutoSuggest } from './AutoSuggest/AutoSuggest.react';
export { ErrorLog } from './ErrorLog/ErrorLog.react';
export { default as IconsBar } from './IconsBar/IconsBar.react';
export { JobDetails, JobEntry, JobGraph } from './Job';
export { default as LogsViewer } from './LogsViewer/LogsViewer.react';
export { default as Menu } from './Menu/Menu.react';
export { default as MultiSelect } from './MultiSelect/MultiSelect.react';
export { default as Notifications } from './Notifications/Notifications.react';
export { default as Panel } from './Panel/Panel.react';
export { ColorProperty } from './Theme';
I have multiple components (screens) connected like this:
import { setNavigationHeader } from './actions';
const MyScreen = () => {
useEffect(() => {
props.setNavigationHeader('MyScreen title');
});
...
}
const mdtp = {
setNavigationHeader
}
export default connect(null, mdtp)(MyScreen);
Is there any way to "inject" this into the component so I can reuse it for multiple components? Maybe with a HOC?
I'm pretty new to React so I don't know what would be the best course of action here.
Also, I would need to be able add more actions to the mapDispatchToProps or to add a mapStateToProps if I want.
The connect function actually returns a HOC, you just need to create it once and reuse it inside your screen components
// navigation.utils.js
import { setNavigationHeader } from './actions';
export const connectScreen = connect(null, {setNavigationHeader});
// MyScreen.js
import { connectScreen } from './navitation.utils'
const MyScreen = ...
export default connectScreen(MyScreen);
// MyScreen2.js
import { connectScreen } from './navitation.utils'
const MyScreen2 = ...
export default connectScreen(MyScreen2);
Currently working with Redux and was wondering if there was a way to require in multiple modules into a single file, which is then exported again as a single module?
For example, in my actions/bookmark.js I group all actions related to bookmarks accordingly:
module.exports = {
fetchBookmarkList: () => {
return {
type: 'FETCH_LIST'
}
},
fetchBookmark: () => {
return {
type: 'FETCH_BOOKMARK'
}
}
}
Then in my actions/index.js file, I require in all groups of actions (which will include bookmark actions as well as others). Then I would like to export the entire file as a single module.
Schematically I had something like this in mind (obviously this code does not work):
actions/index.js:
module.exports = {
require('./bookmark');
require('./tags');
}
The reason that I want to do this is so that I only have to import a single action file that contains all my actions (i.e. the actions/index.js file):
Example component:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../actions';
class BookmarkList extends Component {
constructor(props) {
super(props);
this.props.fetchBookmarkList();
}
render() {
return (
<div></div>
);
}
}
export default connect(null, actions)(BookmarkList);
I see that you es6 modules syntax in components then, why not in your redux files?
export const fetchBookmarkList = () => {
return {
type: 'FETCH_LIST'
}
};
export const fetchBookmark = () => {
return {
type: 'FETCH_BOOKMARK'
}
}
Based on this reference I think it could be possible to re-export everything like this:
export * from './bookmark'
export * from './tags;
But haven't tried it and I could be wrong.
I would NOT recommend you to pass all the actions to mapDispatchToProps, only the actions needed by your component
But you could just use in actions/index.js:
Using the spread operator:
module.exports = {
...require('./bookmark');
...require('./tags');
}
And in ES6 syntax:
actions/index.js:
export * from './bookmark'
export * from './tags'
I am using react native and redux, this is my action:
import EMPLOYEE_UPDATE from './types';
export const employeeUpdate = ({ prop, value }) => {
return (
{
type: EMPLOYEE_UPDATE,
paylaod: { prop, value }
}
);
};
but i get this error:
Actions may not have an undefined "type" property. Have you misspelled a constant?
EDIT:
the types.js file is:
export const LOGIN_USER_FAILED = 'loing_user_failed';
export const SHOW_SPINNER = 'show_spinner';
export const EMPLOYEE_UPDATE = 'employee_update';
You need to import EMPLOYEE_UPDATE from types file like this
import { EMPLOYEE_UPDATE } from './types';
You need to import the const as a named import rather than a default import since you have exported it as a named const.
import {EMPLOYEE_UPDATE} from './types';
See this answer for details on named and default exports:
in reactjs, when should I add brackets when import