Code sharing between React ES6 Classes - reactjs

I'm struggling to dry up a few functions i'm using accross several of my component classes. Mixins are a no-go and I'm struggling to understand what alternative I'm supposed to use. Setting the code up as a module seems promising, but I don't understand how to package it so I can use it to extend several different class.
Say I have:
class functionsToShare {
thingToDo(){
//do a thing
}
}
export default functionsToShare;
I'm assuming in my component class I'd want something like:
import React from 'react';
import functionsToShare from 'some/path'
class SomeComponent extends React.Component{
constructor(props){
super(props);
}
render(){
return (
);
}
}
export SomeComponent
But how do I use the shared class to extend my component? If I declared it inthe class declaration likemy componenet is delcared to extend React.Component that would defeat the reusability... Is there an alternate way I should be looking at?

You can create your shared functions file as a file with several functions that you need to use, each function being exported as a named export. Like this:
export function thingToDo() {
...
}
export function getUserByEmail(email) {
...
}
Save this file as functionsToShare.js, for example.
Then in each React component class (or anywhere else) you can import that functions, just ones you need by:
import {thingToDo} from "./functionsToShare"; // import a function
thingToDo(); // call function
or all of them by:
import * as somename from "./functionsToShare"; // import all functions from that file
somename.thingToDo(); // call specific function

Related

React-Redux-Class extends value #<Object> is not a constructor or null

Class extends value # is not a constructor or null
Error shows up when tried Inheriting a Parent Class which is binded with react-redux "connect" ->
Redux
const mapStateToProps=(state)=>({
.....
});
const mapDispatchToProps=(dispatch)=>{
return {
paymentOver:()=>dispatch(paymentClose()),
}
}
export {
mapStateToProps,mapDispatchToProps
}
Parent Class
import { connect } from "react-redux";
import { mapStateToProps,mapDispatchToProps } from "../../State Management/MappingStates";
Class MainContainer extends Component{
componentDidMount(){
this.props.paymentOver(); //redux action
}
}
export default connect( mapStateToProps,mapDispatchToProps )( MainContainer )
Sub Class
import MainContainer from './MainContainer';
Class Sub extends MainContainer{ //Error showing at this line- Class extends value #<Object> is not a
//constructor or null
render(){
return ......
}
}
export default Sub
Afaik, connected components are function components, so you cannot extends them.
Either way, even if it were a class component, it would be a new Component that just rendered your original class component. So neither way, you could extend this.
In general: in React, you should never extend components - even class components, but use other patterns like higher order components or composition.
Also, the whole ecosystem is shifting to function components for two years now. Unless you have a very good reason to (like maintaining a very legacy code base), you probably should not write class components any more.
That is also the recommendation of the redux style guide: use hooks (useSelector and useDispatch) and function components over connect and class components.
If you are just learning react & redux, you are probably following very outdated sources. For Redux, pleasee look at the official tutorials at https://redux.js.org/tutorials/index

how to export multiple classes in react

Hello i'm trying to export multiple classes in react so they can be all rendered in one page. My group makes each handled a component and now where tying to bring it all together. Problem is that when we try to combine the classes we get errors that they have already been declared. Its all a learning process and while looking for solutions we saw that you can import the components and have them rendered but even looking through documentation we were a bit confused.
import styles from './ViewJobsList.css';
import { Helmet } from 'react-helmet';
import { compA, compB} from './App.js';
class compA extends React.Component {...};
class compB extends React.Component {...};
export default { compA, compB};
Now each class works on its own but together when put like this we get
Parsing error: Identifier 'compA' has already been declared
How can we export these two classes and 1 more in the future?
If you take out this line:
import { compA, compB} from './App.js';
It'll work.
The reason it's not working at the moment is because you're importing and declaring the functions in the same file. You only want to declare or import - not both.
You only want to use an import statement in files where you want the functions to be pulled across from a new file. Export is used on the file where the functions are declared.
Edit: So to import and export how you want, you need to phrase it like this:
In your app.js, you need to phrase it like:
export { compA, compB };
In your index.js, you then need to:
import { compA, compB } from "./app.js"
**Note!! If your app.js is in a different folder, i.e. a components folder, you will need to add the folder route before app.js, so it would be like:
./components/app.js**
That should be all OK - assuming you have the React and appropriate dependencies imported.
Try and delete line 3 in your snippet viz import { compA, compB} from './App.js';

How to call a function from another class React-native

I am trying to call a function from another class it throws an error getValue is not a function. i dont want to use static. I hope there's a solution for it. here's my code
import React, { Component } from "react";
import SecondClass from "./main"
export default class A extends Component{
constructor (props) {
super(props)
onPress = ()=>{
getValue()
}
}
//SecondClass
export default class SecondClass extends Component{
constructor (props) {
super(props)
}
getValues = () => {
alert("Hello")
}
}
I think you need to define the function in the A and then pass the function in the SecondClass component as a prop...
https://www.npmjs.com/package/react-native-simple-events
You can use this library here you can register your function and can trigger from anywhere in app.
For register your function use on("eventID", "listenerID", ()=>{//call getValues}) in class SecondClass
For Trigger your function use trigger("eventID", eventData) in class A
After that remove the listener by using remove("eventID", "listenerID") from class SecondClass
You cannot expect that you can simply call some function in another class because you imported that class. The React way of doing this would be to pass the function as a prop if these are parent-child components. If not, I would highly recommend extracting the common function out from both classes and call them separately.
From the comments, other users have also recommended using static function if you absolutely want to couple the function to Second class.
My main objective is when user press the button then it should call the method from another class and return Hello. Then later i want to set some properties which i not possible in static function. So thats why i dont want to use static function
From your sample code it looks like Second is a React component ? If this class was made to encapsulate certain behavior then I would recommend turning it into a plain javascript class and then instantiate/use wherever necessary.

Is it necessary to create a render function in a react native application?

I have a list of functions that use different react-native's built-in features, I want to create a react-native class that uses those features and only use its functions and those functions will not return anything
What I have already done is returned null from my render function.
but in this case I have to create use refs to call my functions
what I'm trying to achieve is this
export default class Wrapper extends Component{}
and in my screens I want to do this
export default class MyScreen extends Wrapper{
}
or may be
export default class MyScreen extends Component{
componentDidMount(){
Wrapper.myFunction()
}
}
Wrapper.myFuntion() works with all the react native's feature but doesn't render anything in view and only used for data manipulation.
Why dont you create a class which just imports the React features you want, then that class can be called with the functions you want?
If you don't want to run through the lifecycle of React, then don't extend off of a React Component.
For example, create a class:
export class ReactFunctions {
constructor (stuff : any) {
//constructor code
}
public reactFunction1 () {
//react stuff....
}
}
And import it when you need it....
import {ReactFunctions} from ....
Following on from that, I create 'micro-services' and helper classes which don't necessarily have React based functions in. You can separate out common functionality into common modules.

Are there any naming conventions to follow while working with boilerplate code import and export?

export default class SampleClass extends Component {
}
while importing this class which of the following is correct?
import sampleClass(same as class name) from '.module1'; or
import Myclass(Some custome name) from '.module1';
Your component:-
app.js
export default class App extends Component{
//
}
While importing components You should always import as it is:-
import App from "./components/app";
Since you have added redux as a tag so I might guess you arisen this question while working with reducers, if i am not wrong(really sorry if i am wrong).In case of reducers they always return some object (state) a reducer always look like this
reducer-post.js
export default function(){
//return []
}
So while importing reducers you can use any name just like this
import AnyReducer from "./reducers/reducer-post"
Since reducers are functions here so by default they are imported from it, but in the case of components, they were the class so we need to explicitly import them by name.
Using the same name is unnecessary for default exports, but becomes necessary in case of named exports.
So it's better to always use the name defined in export.

Resources