How to re-use a method from one component to the next - reactjs

I have a component that has grown rather large. I decided to break it up into two components, but have found that the component I have split off needs to utilize a method from the original component.
What is the best way to consume a method from inside of an existing component?
Thanks in advance!

Once upon a time, one would have used mixins to achieve what you are looking to do. Since then, this article came out : https://facebook.github.io/react/blog/2016/07/13/mixins-considered-harmful.html
They are still an option in my opinion but require discipline so that you don't overuse the concept.
Other options for you would be:
a) Bring the desired method up one level. By that I mean you could declare it in the container component and pass it along a props to the 2 childrens.
b) If the method is generic enough, declare it in an utility class that you would import in both components. (using static is an option as well)
c) any other innovative way ;) (just to say that these are not the only options)

Extend your base class with in a Split off version. If you use ES6 it would look something like this:
class Base extends React.Component {
renderText () { return 'Hello'}
render(){
return <span>{this.renderText()}</span>
}
}
class SplitOff extends Base {
render() {
return <span>{`${this.renderText()} World`}</span>
}
}
JSFiddle of the above

Related

Calling component in react

I am new in react and i come to this new syntax please help me to understand it better.
class Car extends React.Component {
constructor() {
super();
this.state = {color: "red"};
}
render() {
return <h2>I am a {this.state.color} Car!</h2>;
}
}
root.render(<Car color="red"/>);
I have created a class component and as in object oriented programing we should create the instance of class to use it but here we are not initiating a class instance we just write the name of class in jsx language.
can anyone help me here what's happening behind the scene.
Actually react take cares of it on its own. We dont need to create instance while using recactjs.
please read the explanation here in offcial doc of reactjs.
(There mentioned below sentence.)
"Function components don’t have instances at all. Class components
have instances, but you never need to create a component instance
directly—React takes care of this."
https://reactjs.org/blog/2015/12/18/react-components-elements-and-instances.html
React is a library and does it so you don't have to worry about it.
The syntax you just saw is JSX. It is just syntactic sugar for React.CreateElement. And when you go to the React source code you can see that a constructor is actually called.
return ReactElement(
type,
key,
ref,
self,
source,
ReactCurrentOwner.current,
props,
);
Here ReactElement is a factory method. It creates an object and returns that. But you never have to worry about it.
It is like worrying about addEventListener. How do you know it actually works? :D
PS: There are no real classes in JS. ES6 classes are just an abstraction and are actually created using functions only.

Best place/way to declare static data in React

I am reading through the internet trying to find some performance resolute or preferred method of declaring static data, variables in react so I would like to hear your opinion.
This goes for react stateless and class components.
Let’s say I have an array with colors that I want to use somewhere inside React return().
const colors = ["red, "green", "blue"];
1) Declare it inside of render()
I suppose this is not preferred, snce it will be recreated on every render.
2) Declare it in constructor as a global variable
this.colors = ["red, "green", "blue"];
Nice, but maybe not preferred in some cases to have global variables.
3) Declare it as a return of function placed inside React component but outside of render(). We call the function from React return()
4) I think I saw somewhere using defaultProps.
Is there a best practice?
Few common approaches are to
declare it above a class or in beginning of a file after imports
if its a file specific constants.
const CONST1 = [0,1,2,];
class xxx extends yy {
....
}
or you can keep it in seperate file and import it when its common to many places.
something like
a json file
file a.json
{
"color": "red"
}
usage b.js
import constant from 'constants/a.json';
console.log(constant.color);
or even in global.color = 'red' which i would not advice to use
For class components, I've used the approach of declaring static variables on the class recently.
import React from 'react';
class Example extends React.Component {
// never changes, but may be used in other places, such as parent components
static displayName = 'Example';
state = {
someStateData: 'World'
};
render() {
const { someStateData } = this.state;
// do work
return <p>Hello {someStateData}</p>;
}
}
export default Example;
Well, I think it depends on your needs, most cases 2 and 3 might be enough. I've seen several proyect sources (such as create-react-app, react-native-maps, for instance) and they all handle this consts and "Global resources" in a same way:
They put them in separated files, and they import them as modules in every file where they are needed. I've used this approach and I can tell you is a really good and common practice
I want to bring up this because it's a really good thing:
https://www.npmjs.com/package/reactn
ReactN is a extension of React that includes global state management. It treats global state as if it were built into React itself -- without the boilerplate of third party libraries.
You can use [ global, setGlobal ] = useGlobal() to access the entire global state object.
It works in class, function, and non-react files.
I use it since 2 or 3 years ago, without a glitch.
I know that, given the OP's question, this is overkill. But anyway, I wanted to draw attention into this excellent tool.

How to check what additional props were passed into a react component that were not defined?

I'm wondering if it's okay to access the defined PropTypes in the React component class, by using: this["__proto__"]["constructor"]["propTypes"]
For example if I have this component:
class Hello extends React.Component {
static propTypes = {
name: string
};
render() {
console.log(this.props);
console.log(this["__proto__"]["constructor"]["propTypes"]);
return <h1>Hello {this.props.name}!</h1>;
}
}
A use case would be that if I want to check what additional props were passed into the component that were not explicitly defined.
To be clear, the above DOES WORK, it's more a matter of whether or not this is something that should be avoided - I know this is probably a somewhat opinionated question, but I haven't seen it anywhere else so, thought I'd look for some feedback. If it should be avoided is there a better way?
Accessing object prototype directly using __proto__ is not recommended because this property has never been part of the ECMAString standard. Main vendors did implement it and these days it will likely work in all the environments targeted by your React app.
Usual replacement for it is Object.getPrototypeOf() method which you could use same way:
Object.getPrototypeOf(this).constructor.propTypes
But in any case, you can read static properties of the class directly:
render() {
console.log(Hello.propTypes);
return <h1>Hello {this.props.name}!</h1>;
}
Prefer this better.

Stateless functional component vs. additional render method in a stateful component?

As a really basic example, imagine I wanted to render a div containing some text outside of my render() method. Which of these options would be better?
class StatefulComponent extends Component {
...
render() {
return (
{this.renderTextDiv(this.state.text)}
)
}
renderTextDiv(text) {
return <div>text</div>
}
}
or
class StatefulComponent extends Component {
render() {
return (
<TextDiv text={this.state.text} />
)
}
}
function TextDiv({text}) {
return <div>{text}</div>;
}
Or would you completely pull the stateless component into its own class? Or does it just not matter at all? Does one make testing easier? Readability? Any differences at all?
It does not make any difference in terms of what is being displayed. However, it definitely changes the structure and readability of the code.
For myself, I try to divide the structure into as much Components as possible, and so does Thinking in react suggests. However, if you think that the element does not structurally differ from its parent component and thus does not deserve its own separate component but you require some readability and re-usability, the top code works.
The first one looks more concise in my opinion. You could render html in methods if it's not a big code, or, just a conditional rendering inside the component. Whenever you have some html rendering with a big structure and some functionality, it is always good to separate it into its proper component, because you probably would reuse this code later. Again: If it's not a big code or functionality, it's ok to use html rendering inside a method.

React Native - Is extending a class acceptable in this scenario?

So, I have read multiple times: Composition is Good. Extending is Evil.
Now, I do use composition, basically a lot of stateless components and higher order components, however I do have one particular case where I extend a class.
Instead of every stateless component extending from Component, I am extending from my own BaseComponent, which basically has some helper functions that I use in all of my components.
Like for example:
Analytics helpers
Loggers
Data Fetchers
Configuration
Storage
Theme management
Actions
So far, I am happy with the result. I am looking for any good reason for me to actually break this pattern in the objective to pursuit great code.
Please no "React recommends composition" answers.
Well why not simply use HOC's for each of those pieces?
The big benefit of using HOC's for these kind of situations, is that you can apply them individually, or as a group. You gain a ton of control in how you slice/dice these shared pieces of functionality.
As a simple, example, your logger as an HOC might look something like;
const function loggerHoc(WrappedComponent) {
return class extends Component {
log(message) {
console.log(message); //or other implementation
}
render() {
<WrappedComponent log={this.log} {...this.props}/>;
}
}
}
Now if you had a second HOC of this style for analytics, they can be wrapped on top of one another without issue;
ResultComponent = loggerHoc(analyticsHoc(ChildComponent));
Which you could also write a function to do all of;
const function wrapWithAll(WrappedComponent) {
return loggerHoc(
analyticsHoc(
WrappedComponent
)
);
}
Or you can use individually, as your needs dictate.

Resources