how to open a link in browser - Vue Native - reactjs

There is practically no information about this. I'm trying to use the Linking component from react-native, but there is very little information about using react native components, and I'm not sure if I'm using it right...
Here is what I have in template:
<nb-button :on-press="loadInBrowser">
<nb-text class="source"> Test hyperlink </nb-text>
</nb-button>
And here is in script:
import Linking from "react-native";
export default {
components: {
Linking
},
//data(),
methods: {
loadInBrowser: function () {
Linking.openURL("https://www.google.com");
},
},
}
But is not working, I'm getting this error:
"TypeError: _reactNative.default.openURL is not a function. (In '_reactNative.default.openURL("https://www.google.com")', '_reactNative.default.openURL' is undefined)

This works for me:
Linking.Linking.openURL("https://www.google.com");

Related

Fetching a github repo in react gives a "Module "stream" has been externalized for browser compatibility and cannot be accessed in client code" error

I am currently stuck with a problem trying to fetch github repo data using the octokit npm package.
I use vite to run a dev server and when I try to make a request, the error that i get is:
Uncaught Error: Module "stream" has been externalized for browser compatibility and cannot be accessed in client code.
My React .tsx file looks like this:
import { Octokit, App } from 'octokit'
import React from 'react'
const key = import.meta.env.GITHUB_KEY
const octokit = new Octokit({
auth: key
})
await octokit.request('GET /repos/{owner}/{repo}', {
owner: 'OWNER',
repo: 'REPO'
})
export default function Repos() {
return (
<>
</>
)
}
I have redacted the information for privacy purposes.
If anyone knows how to resolve this issue with vite, please let me know!
Check first if this is similar to octokit/octokit.js issue 2126
I worked around this problem by aliasing node-fetch to isomorphic-fetch. No idea if it works for all usages within octokit, but works fine for my project.
You'll need to install the isomorphic-fetch dependency before making this config change.
// svelte.config.js
const config = { // ... kit: {
// ...
vite: {
resolve: {
alias: {
'node-fetch': 'isomorphic-fetch',
},
},
},
},
};
export default config;
Note: there are still questions about the support/development of octokit: issue 620.

Expo freezes if using ReactNative's StyleSheet

I have encountered a bug with react-native's Stylesheet component. It causes my iphone simulation to stay stuck on expo's logo after loading the js bundle. No errors to be found.
import { Text, View, StyleSheet } from "react-native"
var styles = StyleSheet.create({
innerText: {
color: 'red',
}
})
export var TestComponent = function() {
return (<View><Text style={styles.innerText}>NOW Lets get this working</Text></View>)
}
If I just put the style inline, it works and renders correctly. No freezing after bundle loading.
return (<View><Text style={{color:'red'}}>NOW Lets get this working</Text></View>
One thing to note is that this TestComponent is coming from a node_module. Stylesheet's work as expected in the app's codebase, but fail when coming from this node_module.
The module that exports the TestComponent was using react-native 0.68.0, but the app that uses the module was using react-native 0.64.3. When I downgraded the module to the same react-native version, it worked.
It also worked when updating the app's version instead of downgrading the other, but this time expo gives a warning: Warning: Invalid version react-native#0.68.1 for expo sdkVersion 44.0.0. Use react-native#0.64.3

How to enable prop-types in production for a React Storybook for the Docs addon

By default prop-types do not run in production for a react app. I realize this is a good thing to improve performance. However, we have a Storybook that we have built and are deploying it to a static site. Storybook has an addon called Docs that detects the prop-types for components and creates a table of the prop-types for easy to read documentation.
When running the storybook locally, everything works perfectly. The prop-types are detected and this table is generated.
SpinningLoader.propTypes = {
color: PropTypes.string,
size: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
};
However, since prop-types are disabled in production by default. They cannot be detected when the storybook is deployed to a static site.
Is there a way to enable prop-types in production? Or some other workaround?
It's a little difficult to know without seeing more of your setup. If you're building it with the default storybook commands without and additional configuration it should "just work"...as far as I can tell.
As mentioned in a comment, Storybook has a specific build command you can add to your package.json to export it as a static app:
"scripts": {
"build-storybook": "build-storybook -c .storybook -o .out"
}
If you're using that command and it's still not working, are you using any custom webpack/build workflow, and can you post those as well?
I've built a minimal repository for reference, which may be helpful in comparing your setup. Besides the packages in package.json it's really only 3 files; Storybook config, a React component, and a Component Story:
.storybook/main.js
module.exports = {
stories: ['../src/**/*.stories.[tj]s'],
addons: ['#storybook/addon-docs'],
};
src/components/message/message.js
import React from 'react'
import PropTypes from 'prop-types'
const Message = function Message({ text, color }) {
return (<div style={{ color }}>{text}</div>)
}
Message.propTypes = {
text: PropTypes.string.isRequired,
color: PropTypes.string.isRequired,
}
export default Message
src/components/message/message.stories.js
import React from 'react'
import Message from './message'
export default { title: 'Message', component: Message }
export const withText = () => <Message text="Hello World" color="green" />
If I run the build-storybook command, cd .out, and then npx live-server, I see the static-built storybook site, with my Message component, and the 'Docs' tab that includes the prop-types:
Full repository for reference
https://github.com/BenjaminWFox/react-storybook
A workaround would be to manually specify the information you want to display in the table for each component using ArgTypes: https://storybook.js.org/docs/react/api/argtypes. Then you can continue with the documentation with that approach.
Another option would be to complete and publish the storybook while the app is still in development. This way you will have the prop-types detected and the table generated for you, then you can later build your app for production.
This is how you would declare the argTypes in the first option
// Button.stories.js
export default {
title: 'Button',
component: Button,
argTypes: {
label: {
description: 'overwritten description',
table: {
type: {
summary: 'something short',
detail: 'something really really long'
},
defaultValue: { summary: 'default-label' }
},
control: {
type: 'text',
},
},
},
};
This is the result
In case anyone runs into this issue again, setting NODE_ENV to development, as suggested here https://github.com/storybookjs/storybook/issues/8140#issuecomment-621314565, solved our problems
The issue was ultimately caused by including the transform-react-remove-prop-types plugin in our babel.config.js production environment. Without propTypes to read, there's nothing to display.
'propTypes' is a useful feature through which we can validate typechecking of props in React but it also unnecessarily creates runtime overhead. It
downgrades the apps performance.
That is the reason it is NOT available in production.
It has been made to help developers especially in a team, to find out if there is any wrong type of props been passed to the component, while writing code during the development environment.
It does not add any extra functionality. It will also add extra lines of code unnecessarily.
By keeping it in the production flow it will defeat the whole purpose.
Whether you also use Flow/typescript for typechecking, there purpose are all same.
refer: https://reactjs.org/docs/typechecking-with-proptypes.html
Now, your issue is similar to the below known issue, kindly refer below:
https://github.com/storybookjs/storybook/issues/1661

React application with external plugins

I'm building a React application bundled using Parcel or Webpack.
The application should be able to embed external React components
developed by third-parties and hosted elsewhere as modern javascript modules:
// https://example.com/scripts/hello-plugin.js
import React from 'react';
export default class HelloPlugin extends React.Component {
render() {
return "Hello from external plugin!";
}
}
Host application loads these components using asynchronous import like this, for example:
// createAsyncComponent.tsx
import * as React from 'react';
import { asyncComponent } from 'react-async-component';
export default function createAsyncComponent(url: string) {
return asyncComponent({
resolve: () => import(url).then(component => component.default),
LoadingComponent: () => <div>Loading {url}....</div>,
ErrorComponent: ({ error }) => <div>Couldn't load {url}: {error.message}</div>,
})
}
But looks like bundlers don't allow importing arbitrary urls as external javascript modules.
Webpack emits build warnings: "the request of a dependency is an expression" and the import doesn't work. Parcel doesn't report any errors, but fails when import(url) occurs at runtime.
Webpack author recommends using scriptjs or little-loader for loading external scripts.
There is a working sample that loads an UMD component from arbitrary URL like this:
public componentDidMount() {
// expose dependencies as globals
window["React"] = React;
window["PropTypes"] = PropTypes;
// async load of remote UMD component
$script(this.props.url, () => {
const target = window[this.props.name];
if (target) {
this.setState({
Component: target,
error: null,
})
} else {
this.setState({
Component: null,
error: `Cannot load component at ${this.props.url}`,
})
}
});
}
Also, I saw a similar question answered a year ago where the suggested approach also involves passing variables via a window object.
But I'd like to avoid using globals given that most modern browsers support modules out of the box.
I'm wondering if it's possible. Perhaps, any way to instruct the bundler that my import(url) is not a request for the code-split chunk of a host application, but a request for loading an external Javascript module.
In the context of Webpack, you could do something like this:
import(/* webpackIgnore: true */'https://any.url/file.js')
.then((response) => {
response.main({ /* stuff from app plugins need... */ });
});
Then your plugin file would have something like...
const main = (args) => console.log('The plugin was started.');
export { main };
export default main;
Notice you can send stuff from your app's runtime to the plugin at the initialization (i.e. when invoking main at the plugin) of the plugins so you don't end up depending on global variables.
You get caching for free as Webpack remembers (caches) that the given URL has already loaded so subsequent calls to import that URL will resolve immediately.
Note: this seems to work in Chrome, Safari & firefox but not Edge. I never bothered testing in IE or other browsers.
I've tried doing this same sort of load with UMD format on the plugin side and that doesn't seem to work with the way Webpack loads stuff. In fact it's interesting that variables declared as globals, don't end up in the window object of your runtime. You'd have to explicitly do window.aGlobalValue = ... to get something on the global scope.
Obviously you could also use requirejs - or similar - in your app and then just have your plugins follow that API.
Listen to the Webpack author. You can't do (yet) what you're trying to do with Webpack.
You will have to follow his suggested route.

Sonarqube : Create a custom page using react

I would like to create a custom page using react but I cannot find the documentation to do this. On the Sonarqube documentation, there only the way to create a custom page using javascript only and I don’t understand how the example plugin works with react.
Can you tell me if there is a documentation that I can use.
Short answer: There isn't. There is barely anyone (no one in fact, as far as I've seen) using custom pages currently.
However, it IS possible. You need to create a react project with Webpack (or a similar JS packager).
I also recommend using Create-React-App. This fixes a lot of the setup for you. After that, in your index.js you use the example code from the SonarQube wiki.
Here is an example:
/*
PRODUCTION ENTRYPOINT
*/
import React from 'react';
import ReactDOM from 'react-dom';
import Project from './components/Project';
import './main.css';
window.registerExtension('myplugin/coverage', function (options) {
appendCustomCSS();
let isDisplayed = true;
window.SonarRequest.getJSON('/api/measures/component', {
component: options.component.key,
metricKeys: 'coverage'
}).then(function (response) {
if (isDisplayed) {
let obj = JSON.parse(response.component.measures[0].value);
let div = document.createElement('div');
render(obj, div);
options.el.appendChild(div);
}
});
return function () {
isDisplayed = false;
};
});
function appendCustomCSS() {
let fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", "/static/myplugin/coverage.css");
document.head.append(fileref);
}
function render(objectArray, container) {
ReactDOM.render(<div className="Coverage"><Project objects={objectArray}/></div>, container);
}

Resources