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

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;

Related

Simplify this repeating code pattern on class components

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.

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.

Can't find an internal method in a React container component

I'm trying to get AJAX-retrieved data into a parent React component so it can be fed down to a child component. I'm using the popular pattern for this defined here where a comment list is used as the example:
components/CommentList.js
import React from 'React';
export class CommentList extends React.Component {
constructor(props) {
super(props);
}
render() {
return <ul> {this.props.comments.map(renderComment)} </ul>;
}
renderComment({body, author}) {
return <li>{body}—{author}</li>;
}
}
components/CommentListContainer.js
import React from 'React';
import { CommentList } from './CommentList';
export class CommentListContainer extends React.Component {
constructor() {
super();
this.state = { comments: [] }
}
componentDidMount() {
$.ajax({
url: "http://get/some/api",
dataType: 'json',
success: function(comments) {
this.setState({comments: comments});
}.bind(this)
});
}
render() {
return <CommentList comments={this.state.comments} />;
}
}
index.js: the entry point for webpack
import React from 'react'
import { render } from 'react-dom'
import { CommentListContainer } from './components/CommentListContainer';
window.React = React;
render(
<CommentListContainer />,
document.getElementById('nav__react-target')
)
When doing all this, I get the following error:
Uncaught ReferenceError: renderComment is not defined
I've move the methods around as well as tweaked the importing of dependencies in various spots with no luck. Any ideas?
Thanks in advance.
You don't have unguarded references to sibling methods with ES2015 classes (as you do in Java / C#, etc.) - instead you need to explicitly reference this to get at the methods of the class:
render() {
// I changed map(renderComment) to map(this.renderComment)
return <ul>{this.props.comments.map(this.renderComment)}</ul>;
}

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

how can I extend a react-bootstrap component

I want to extend the react-bootstrap component and modify some of the prototype to achive my component.Here is my code:
import React from 'react';
import { Pagination } from 'react-bootstrap';
export default class myPagination extends Pagination {
constructor(props) {
super(props);
}
render() {
return <div>test</div>;
}
}
But here is a error:Cannot read property 'bind' of undefined
Maybe the Pagination component is created by React.createClass so I can't extends the component?
How can I solve the problem?

Resources