Simplify this repeating code pattern on class components - reactjs

I'm currently implementing accessibility (VoiceOver/Talkback) support for my application, and I use AccessibilityInfo.setAccessibilityFocus (see official docs) quite a lot which requires a reactTag, which I can only get by using findNodeHandle as per this answer.
This means that I keep repeating the same pattern involving quite a few function calls, over and over on many different components. I originally tried to move the stored references and the call to set focus to my state manager (using MobX in this case) but I ended up getting a lot of failed findNodeHandle calls because sometime the component had unmounted before the call was made.
This is the gist of what I keep repeating:
import React, {Component} from 'react'
import {
...
findNodeHandle,
AccessibilityInfo
...
} from 'react-native';
class Sample extends React.Component {
constructor(props) {
super(props)
this.accessibilityRef = null;
}
...
componentDidMount() {
this.setAccessibilityFocus()
}
componentDidUpdate() {
this.setAccessibilityFocus()
}
setAccessibilityRef(el) {
this.accessibilityRef = el
}
setAccessibilityFocus() {
if (this.accessibilityRef) {
const reactTag = findNodeHandle(this.accessibilityRef);
AccessibilityInfo.setAccessibilityFocus(reactTag);
}
}
render() {
return (
<View ref={this.setAccessibilityRef} accessible={true}>
...
</View>
)
}
}
Would it be possible to somehow make something reusable out of this? Maybe a decorator or as a class extension so that I can reuse it?

Yes, you can...
Let, SampleWrapper.js is your wrapper.
import React, {Component} from 'react'
import {
...
findNodeHandle,
AccessibilityInfo
...
} from 'react-native';
export default class SampleWrapper extends Component {
constructor(props) {
super(props)
this.accessibilityRef = null;
}
...
componentDidMount() {
this.setAccessibilityFocus()
}
componentDidUpdate() {
this.setAccessibilityFocus()
}
setAccessibilityRef(el) {
this.accessibilityRef = el
}
setAccessibilityFocus() {
if (this.accessibilityRef) {
const reactTag = findNodeHandle(this.accessibilityRef);
AccessibilityInfo.setAccessibilityFocus(reactTag);
}
}
render() {
return (
<View ref={this.setAccessibilityRef} accessible={true}>
{this.props.children}
</View>
)
}
}
Now, assume you want to use the above wrapper in your Sample.js
import React, {Component} from 'react'
import SampleWrapper from './path/to/SampleWrapper'
class Sample extends Component {
constructor(props) {
super(props)
}
render() {
return (
<SampleWrapper>
....
</SampleWrapper>
)
}
}
You can put ref s and then you can control it as you expect.
PS: I didn't test this before posting. Hope this will work and help you. If you have any problems regarding this answer or if you want to add something more and you have doubts about how to do it, please just comment on it here.

Related

How to use eval() to import components dynamically in react-native

I am trying to import a class component from a js file placed in external storage dynamically,
sample.js
import React, { Component } from 'react';
import { View, Text } from 'react-native';
var HeaderComponent=eval(`class HeaderComponent extends Component {
constructor(props) {
super(props);
}
render() {
return <Text>This is header</Text>;
}
}`)
class App extends Component {
constructor(props) {
super(props);
}
render() {
return <View>{HeaderComponent}</View>;
}
}
when i run the above code, I got following error,
SyntaxError: Unexpected token '<'
this error apparently indicates the following return statement(which is inside eval()),
return <Text>This is header</Text>;
May i know if this is the right way of doing dynamic import?. If not, Please let me know the right way of doing the dynamic import in react-native.
The eval() is basically a function that is used for doing Arithmetic operations, It can’t used for import a Component or any thing else,
here's a link from where you can learn about eval()
For import component you can do that with several ways
import statement:
import <Your Component Name> from '<Your Component Path>'
require()
const <Your Component Name> = require('<Your Component Path>')
you just need to add one of the above line at top of the files where you've declared other imports
use import/export keywords. add export at the end of the file, and import at the top
import React, { Component } from "react";
import { Text, View } from "react-native";
class HeaderComponent extends Component {
constructor(props) {
super(props);
}
render() {
return <Text>This is header</Text>;
}
}
class Test extends Component {
constructor(props) {
super(props);
}
render() {
return <View><HeaderComponent/></View>;
}
}
export default Test;

Class variables in REACT

Does class variables in a class need to be a part of the stateObject? I tried below with no luck. Here there is samples with simple variables so I am kind of surprice below does not work (alert says undefined)?
https://www.w3schools.com/react/react_es6.asp
https://codesandbox.io/s/jovial-glade-lfv4f?fontsize=14&hidenavigation=1&theme=dark
import React, { Component } from "react";
class Test extends Component {
constructor(props) {
super(props);
this.variable = "works";
}
clicked() {
alert(this.variable);
}
render() {
return <div onClick={this.clicked}>CLICK ME</div>;
}
}
export default Test;
You need to use bind() call to make it work.
constructor(props) {
super(props);
this.variable = "works";
this.clicked = this.clicked.bind(this);
}
for more information on this checkout Handling events in React
Why you have to bind here? so this is because you are using ES6 syntax for your components, and in ES6 class methods are not bound to classes by default, and to be able to use this keyword inside your methods and make it refer to the class instance you have bind your method to the class like in this answer.
import React, { Component } from "react";
class Test extends Component {
constructor(props) {
super(props);
this.variable = "works";
}
clicked = () => {
alert(this.variable);
}
render() {
return <div onClick={this.clicked}>CLICK ME</div>;
}
}
export default Test;
You can choose not to bind but you need to be adding fat-arrow function syntax in order to make it work.

Proper way of defining/initializing state in reactjs or react-native

So far I understand there are two ways to define state in react class.
The first as many people use them, is as follows:
import React, { Component } from "react";
import { View, Text } from "react-native";
export default class Test extends Component {
constructor (props) {
super(props)
this.state = {
text: 'hello'
}
}
render() {
return (
<View>
<Text>{this.state.text}</Text>
</View>
);
}
}
The second one is as follows:
import React, { Component } from "react";
import { View, Text } from "react-native";
export default class Test extends Component {
state = {
text: "hello"
}
render() {
return (
<View>
<Text>{this.state.text}</Text>
</View>
);
}
}
The difference is at using constructor or not. What is the effect and is there any difference at all between the two? If there is, which one should I use?
Thank you!
Both methods are correct. Make sure you have support for class properties enabled in the babelrc. If you are using CRA both will work. Constructor one is better on the eyes if you want to seed the initial state from props.
Both methods are fine. Second one is the short-hand method

How to access state of one component into another component in react

import React, { Component } from 'react';
class one extends React.Component
{
constructor()
{
super();
this.state = {
number:26
}
}
render()
{
return(
<div></div>
);
}
}
export default one;
import React, { Component } from 'react';
import one from './one'
class HomePage extends React.Component
{
render()
{
return(
<div>{one.state.number}</div>
);
}
}
export default HomePage;
is it possible to access number state
is there any way to access state of one component into another component?
please suggest me if any solution is present.
As Shubam has explained it, Though I would like to form it as a complete answer
First of all, I would like to let you know that Never Use lowercase letters to name your React Components.So name your component to One instead of one.
Now Comming back to your question:-
No This is not Possible, If your app contains few components then it's better to pass the state object as the props, But if your app contains too many components then better to use predictable state containers like Redux or Flux rather than passing state as props.
So you may apply these changes and I hope You will get What You Desire:-
One Component:-
import React, { Component } from 'react';
import Homepage from './homepage';
class One extends React.Component
{
constructor()
{
super();
this.state = {
number:26
}
}
render()
{
return(
<Homepage data={this.state}/>
);
}
}
export default One;
Homepage Component:-
import React, { Component } from 'react';
class Homepage extends React.Component
{
render()
{
console.log("this is homepage",this.props);
return(
<div>{this.props.data.number}</div>
);
}
}
export default Homepage;
Please Raise Your doubts if any, Or if you find any error in it.

Click event in ReactJS error: imports/ui/ParentComponent.jsx:5:16: Unexpected token (5:16)

I am trying to learn Event in ReactJS.
I created 2 components
ChildComponent is
import React, { Component } from 'react';
// App component - represents the whole app
export default class ChildComponent extends Component {
render() {
return (
<button onClick={this.props.onBannerClick}>Click me!</button>
);
}
}
And ParentComponent is
import React, { Component } from 'react';
import ChildComponent from './ChildComponent.jsx'
// App component - represents the whole app
export default class ParentComponent extends Component {
performMagic: function() {
alert('TAADAH!');
},
render() {
return (
<BannerAd onBannerClick={this.performMagic} />
);
}
}
but I got the error
Errors prevented startup:
While building for web.browser:
imports/ui/ParentComponent.jsx:5:16: Unexpected token (5:16)
Your application has errors. Waiting for file change.
I think the error is from
performMagic: function() {
alert('TAADAH!');
},
But I do know what the error is.
By the way, can anybody recommends me good debug tools for ReactJS?
Because you're using the ES6 syntax you'll have to bind the function to the instance using the following approach.
constructor(props) {
super(props)
this.performMagic = this.performMagic.bind(this)
}
This will allow you to use the this keyword in the onClick call
import React, { Component } from 'react';
import ChildComponent from './ChildComponent.jsx'
// App component - represents the whole app
export default class ParentComponent extends Component {
constructor(props) {
super(props)
this.performMagic = this.performMagic.bind(this)
}
performMagic() {
alert('TAADAH!');
}
render() {
return (
<BannerAd onBannerClick={this.performMagic} />
);
}
}
Need to write:
performMagic () {
alert('TAADAH!');
},
You need to use new sintax for functions, when write class which is new sintax.
EDIT: You can use "React Developer Tools" chrome extension and gaearon "redux-devtools" for development.
You need to use the new ES6 syntax when making your React Component a class. Use
performMagic() {
alert('TAADAH!');
}
make sure you don't put a comma after the function

Resources