How to get files uploaded on FTP server with React native? - reactjs

Actually, I want to get the files with directory structure uploaded on FTP server using React-native.
I have tried to find libraries but I didn't find anything related to it.
So can you please help me with this problem?
import React, { Component } from 'react';
import { StyleSheet, View, Button } from 'react-native';
import FTP from 'react-native-ftp';
export default class App extends Component {
onButtonpress() {
FTP.setup("IP", 21) //Setup host
FTP.login("username", "password").then(
(result) => {
FTP.list(".").then(
(result) => {
console.log(result);
}
);
},
(error) => {
alert(error);
}
)
}
render() {
return (
<View >
<Button onPress={this.onButtonpress.bind(this)} title="hi" />
</View>
);
}
}
Here is the sample i have tried but i got error while impoting 'react-native-ftp'.
I got error "Could not find declaration for module 'react-native-ftp'".

The error you encounter is because of react-native-ftp functions are not available on ios - they are not implemented. You need to fork the repo and implement them to work with ios too.
and then:
You can download a file like below using react-native-ftp:
FTP.downloadFile("./nameOfFileToBeDownloaded","localPathWhereItWillBeSaved")
.then(result=>console.log(result))
.catch(error=>alert(error))
Or upload with uploadFile:
FTP.uploadFile("./nameOfFileToBeUploaded","remotePathWhereItWillBeSaved")
.then(result=>console.log(result))
.catch(error=>alert(error))
If you want entire folder, you can zip it first with react-native-zip-archive and the upload just the zip.

Related

Trying to access from React to my websocket which is Django channels but it raises error "No route found"

My websocket works because i tested it from django side white simple chat app. The route also works which is http://localhost:8000/chat/room. But It doesnt work on react side. It says No route found for path 'chat/myroom'. I've been trying to solve this for 2 hours, as a last hope, I wanted to ask here.
My routing.py file
from django.urls import re_path
from api import consumers
websocket_urlpatterns = [
re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()),
]
My roomPage.js file
`import React from "react";
import useWebSocket, { ReadyState } from "react-use-websocket";
import { useParams } from "react-router-dom";
export default function RoomPage() {
const { readyState } = useWebSocket("ws://127.0.0.1:8000/chat/myroom", {
onOpen: () => {
console.log("Connected!");
},
onClose: () => {
console.log("Disconnected!");
}
});
const connectionStatus = {
[ReadyState.CONNECTING]: "Connecting",
[ReadyState.OPEN]: "Open",
[ReadyState.CLOSING]: "Closing",
[ReadyState.CLOSED]: "Closed",
[ReadyState.UNINSTANTIATED]: "Uninstantiated"
}[readyState];
return (
<div>
<span>The WebSocket is currently {connectionStatus}</span>
</div>
);
}`
I tried on django side and it worked! But react side doesn't working
After +10 hours i finally found the solution and I want to kill myself! The only problem is calling websocket without "end slash"
Wrong!
useWebSocket("ws://127.0.0.1:8000/chat/myroom"
Works
useWebSocket("ws://127.0.0.1:8000/chat/myroom/"

Loading a custom font on React Native Expo gives an error

So I am trying to create an app with React Native Expo CLI. I have installed the blank version. I am trying to import the Open Sans typeface into my application. I have done the following steps so far:
Made a folder called "fonts" inside of my "assets" folder, placed the ttf file for Open Sans font inside of it.
Added the following code in my App.js file
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import * as Font from 'expo-font';
export default class App extends React.Component {
constructor() {
super();
this.state = {
fontLoaded: false
};
}
async componentDidMount() {
try {
await Font.loadAsync({
'OpenSans': require('./assets/fonts/OpenSans.ttf')
});
this.setState({ fontLoaded: true });
}
catch( error ) {
console.log(error)
}
}
render() {
return(
<View>
<Text style={styles.text}>Test</Text>
</View>
);
}
}
const styles = StyleSheet.create({
text: {
fontFamily: 'OpenSans',
}
});
Unfortunately, I'm getting an error and all the solutions that I saw on the internet didn't help me. The error which I get is the following:
fontFamily "OpenSans" is not a system font and has not been loaded through Font.loadAsync.
- If you intended to use a system font, make sure you typed the name correctly and that it is supported by your device operating system.
- If this is a custom font, be sure to load it with Font.loadAsync.
- node_modules\react-native\Libraries\YellowBox\YellowBox.js:59:8 in error
- node_modules\expo\build\environment\muteWarnings.fx.js:27:24 in error
- ... 24 more stack frames from framework internals
You are loading the font after the app is mounted, that why you have that error.
your render method should look something like this:
render() {
if (!this.state.fontLoaded) {
return (<View>{/*some loader*/}</View>);
}
return(
<View>
<Text style={styles.text}>Test</Text>
</View>
);
}

How to run React JS build in React-Native Webview?

I created complete offline ReactJS web application and I want to run it from android application from Web View using React-Native.
I followed the following procedure to do so:
1. I created a compiled ReactJS web application got the build using the following command:
npm run build
Then I created react-native project and placed the build folder with following architecture
I updated App.js with the following content:
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, WebView} from 'react-native';
import {roscon} from "./build/index.html";
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View style={{height: 300, width: 300,overflow:'hidden' }}>
<WebView
source={{uri: roscon}}
scalesPageToFit={true}
domStorageEnabled={true}
javaScriptEnabled={true}
startInLoadingState={true}
/>
</View>
);
}
}
After running this code I expected it to run my ReactJS Web application, instead I got white screen.
Can you please tell what can be the causing issues and how i can make my ReactJS Web App run on react-native?
Note: I was able to run generated build folder using npm command
serve -s build
But I still can't figure out how to port it to react-native project as WebView
After research and testing, I found a solution.
The main issue i found was the compiled build folder is rendered as static html. And it needed a server to serve pages.
So, I followed this link for getting build project to get it up and running
Then, integrating it with nodejs Android Project Samples to get my build folder running in android as a Webview.
Note: I also tried react-snapshot and react-snap but they didn't gave satisfactory results.
Try to require the html file correctly and pass it in to source prop in this way:
<WebView
source={require('./build/index.html')}
/>
Install
npm install react-native-react-bridge
These are used to render React app in WebView
npm install react-dom react-native-webview
Requirements
react 16.8+
react-native 0.60+
Usage
Fix metro.config.js to use babelTransformer from this library.
module.exports = {
transformer: {
babelTransformerPath:
require.resolve('react-native-react- >.
.bridge/lib/plugin'),
...
},
};
Make entry file for React app. web.js
import React, { useState } from "react";
import {
webViewRender,
emit,
useSubscribe,
} from "react-native-react-bridge/lib/web";
const Root = () => {
const [data, setData] = useState("");
// useSubscribe hook receives message from React Native
useSubscribe((message) => {
if (message.type === "success") {
setData(message.data);
}
});
return (
<div>
<div>{data}</div>
<button
onClick={() => {
// emit sends message to React Native
// type: event name
// data: some data which will be serialized by JSON.stringify
emit({ type: "hello", data: 123 });
}}
/>
</div>
);
};
// This statement is detected by babelTransformer as an entry point
// All dependencies are resolved, compressed and stringified into one file
export default webViewRender(<Root />);
Use the entry file in your React Native app with WebView.
import React from "react";
import WebView from "react-native-webview";
import { useBridge } from "react-native-react-bridge";
import webApp from "./WebApp";
const App = () => {
// useBridge hook create props for WebView and handle communication
// 1st argument is the source code of React app
// 2nd argument is callback to receive message from React
const { ref, source, onMessage, emit } = useBridge(webApp, (message) => {
// emit sends message to React
// type: event name
// data: some data which will be serialized by JSON.stringify
if (message.type === "hello" && message.data === 123) {
emit({ type: "success", data: "succeeded!" });
}
});
return (
<WebView
// ref, source and onMessage must be passed to react-native-webview
ref={ref}
source={source}
onMessage={onMessage}
/>
);
};

SnapSVGAnimator.js generates errors when loading in React web app

SnapSVG extension for Adobe Animate.cc 2017 is able to create interactivity and animations for the web. I'm currently trying to use an exported SnapSVG Adobe Animate.cc project in my REACT JS WebApplication.
What I've done so far:
Imported snapsvg-cjs from npm( modified snapsvg to use succesfull in React)
Imported axios to load custom json file generated from SnapSVG extension in Animate.cc
Excluded minified code with eslintignore from SnapSVGAnimator. lib, generated while publishing SVG animation from Animate.cc to work properly without the ESlinting warnings.
Create a componentDidMount function
current code:
import React, {Component} from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { SVGAnim } from './SnapSVGAnimator.js';
import snapsvg from 'snapsvg-cjs';
componentDidMount(){
axios.get(jsonfile)
.then(response => {
const json = response.request.responseText;
const comp = new SVGAnim(json);
console.log(comp)
});
}
Problem
Following error appears while I log const comp.
Uncaught (in promise) TypeError:
_SnapSVGAnimator.SVGAnim is not a constructor
During the publish render in Animate.cc there are two libs generated; snapsvg.js and SVGAnimator.js
You can import snapsvg-cjs from NPM but SVGAnimator.js isn't available. Importing SVGAnimator.js with the ES6 approach from a curtain directory in your ReactApp isn't possible, not even by excluding it from linting with /* eslint-disable */ 1000 warnings still appears.
Instead of that, add the code to your index.html file, located in the public folder this way
(I've used create-react-app to build this project):
<script type="text/javascript" src="%PUBLIC_URL%/libs/SnapSVGAnimator.min.js"></script>
This is the working code:
import React, { Component } from 'react';
//axios for asnyc usage*/
import axios from 'axios';
//Snapsvg-cjs works out of the box with webpack
import Snapsvg from 'snapsvg-cjs';
//snap.json is located in the public folder, dev-build folder(ugly approach).
let jsonfile = "snap.json";
class SVGAnimator extends Component {
constructor(props){
super(props);
this.state = {
data: ''
}
}
componentDidMount(){
axios.get(jsonfile)
.then(response => {
this.setState({ data: response.data })
});
}
getSVG(){
if(this.state.data){
const container = document.getElementById('container');
const SVG = new window.SVGAnim(this.state.data, 269, 163, 24)
container.appendChild(SVG.s.node);
}
}
render() {
return (
<div id="container">
{ this.getSVG()}
</div>
);
}
}
export default SVGAnimator;

react-native error "application appname has not ben registered" onsublime text

I am new in react native programming, I am trying to make this work.
import React, { Component } from 'react';
import { AppRegistry, Text } from 'react-native';
class AppName extends Component {
render() {
return (
<Text>Hello world!</Text>
);
}
}
AppRegistry.registerComponent('AppName', () => AppName);
but I am facing below issue : application appname has not been registered
i tried the following solution but its not working for me Application main thread has not been registered in react native
The issue here is that 'AppName' on the last line is not the same as what you named your project on creation. It should be the same name as your project directory. Capitalization matters. Looking at your error message, you named your project appname.
For example if you create a project:
react-native init appname
And if your class is still the same name:
class AppName extends Component {
Your last line should be:
AppRegistry.registerComponent('appname', () => AppName);

Resources