Showcase view on first launch of react native app - node.js

I have been looking for a guide to create a showcase view on first launch of my react native app, I might don't know the correct word for it, actually it's a user guide for features on first launch, it has a direction towards the icon and it's details, I haven't found anything on it, it'll be a great help if anyone guide me about that, thanks

Here is some demo code from the doc of react-navigation. I think it's similar to your case.
if (state.isLoading) {
// We haven't finished checking for the token yet
return <SplashScreen />;
}
return (
<Stack.Navigator>
{state.userToken == null ? (
// No token found, user isn't signed in
<Stack.Screen
name="SignIn"
component={SignInScreen}
options={{
title: 'Sign in',
// When logging out, a pop animation feels intuitive
// You can remove this if you want the default 'push' animation
animationTypeForReplace: state.isSignout ? 'pop' : 'push',
}}
/>
) : (
// User is signed in
<Stack.Screen name="Home" component={HomeScreen} />
)}
</Stack.Navigator>
);
Add a firstLaunch state to true first and then set it to false and save in the asyncstorage.Something like:
let firstLauch = await AsyncStorage.getItem("firstLauch");
firstLauch = JSON.parse(firstLauch);
firstLauch = firstLauch === false?firstLauch:true
let [isFirstLauch,setIsFirstLauch]=useState(firstLauch);
return (
<Stack.Navigator>
{isFirstLauch ? (
// No token found, user isn't signed in
<Stack.Screen
name="FirstLauch"
component={FirstLauchScreen}
/>
) : (
<Stack.Screen name="Home" component={HomeScreen} />
)}
</Stack.Navigator>
);
Don't forget to set firstLauch to false in your firstLauchScreen.

Have a try with the popular npm package for creating your showcase of first launch https://www.npmjs.com/package/react-native-copilot

Related

How do I avoid visual bug when navigating from one screen to another? - React Native Expo

I'm creating a sign in screen and a create account screen on my application. I have buttons that go back and forth to each other. Both screens work fine individually. When I do this, there can often be a visual error like so:
My App.js Code:
const App = () => {
return (
<NavigationContainer theme={theme}>
<Stack.Navigator screenOptions={{ headerShown: false}} initialRouteName="CreateAccountScreen">
<Stack.Screen name ="CreateAccountScreen" component={CreateAccountScreen} />
<Stack.Screen name ="SignInScreen" component={ SignInScreen } />
</Stack.Navigator>
</NavigationContainer>
);
}
Code from each Screens button that goes back and forth:
onSignUpButtonPressed = () => {
navigation.navigate("SignInScreen")
}
onCreateAccountButtonPressed = () => {
navigation.navigate("CreateAccountScreen")
}
Displays seem to overlay themselves in a bad way
I've tried a bunch of things and this has happened on several screens...
Your initialRouteName is set up as we can see but on your Stack.Screen you also give it the Component attribute.
I did a test based on how my navigation looks and I did not get the visual bug you showed so I think if you removed the component attribute and maybe just put the component tag inside your Stack.Screen as shown below it might work. Just imagine my Home is your CreateAccountScreen.
<Stack.Navigator
initialRouteName='Home'
>
<Stack.Screen
name="Home"
options={{
headerShown: false,
}}
>
{props => <Home {...props} username='Bella' />}
</Stack.Screen>
You also dont have the code in your question to define Stack like this:
const Stack = createStackNavigator();

Linking to a different url using Link of react router dom [duplicate]

Since I'm using React Router to handle my routes in a React app, I'm curious if there is a way to redirect to an external resource.
Say someone hits:
example.com/privacy-policy
I would like it to redirect to:
example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies
I'm finding exactly zero help in avoiding writing it in plain JavaScript at my index.html loading with something like:
if (window.location.path === "privacy-policy"){
window.location = "example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies"
}
Here's a one-liner for using React Router to redirect to an external link:
<Route path='/privacy-policy' component={() => {
window.location.href = 'https://example.com/1234';
return null;
}}/>
It uses the React pure component concept to reduce the component's code to a single function that, instead of rendering anything, redirects browser to an external URL.
It works both on React Router 3 and 4.
With Link component of react-router you can do that. In the "to" prop you can specify 3 types of data:
a string: A string representation of the Link location, created by concatenating the location’s pathname, search, and hash properties.
an object: An object that can have any of the following properties:
pathname: A string representing the path to link to.
search: A string representation of query parameters.
hash: A hash to put in the URL, e.g. #a-hash.
state: State to persist to the location.
a function: A function to which current location is passed as an argument and which should return location representation as a string or as an object
For your example (external link):
https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies
You can do the following:
<Link to={{ pathname: "https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies" }} target="_blank" />
You can also pass props you’d like to be on the such as a title, id, className, etc.
There isn’t any need to use the <Link /> component from React Router.
If you want to go to external link use an anchor tag.
<a target="_blank" href="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies">Policies</a>
It doesn't need to request React Router. This action can be done natively and it is provided by the browser.
Just use window.location.
With React Hooks
const RedirectPage = () => {
React.useEffect(() => {
window.location.replace('https://www.google.com')
}, [])
}
With React Class Component
class RedirectPage extends React.Component {
componentDidMount(){
window.location.replace('https://www.google.com')
}
}
Also, if you want to open it in a new tab:
window.open('https://www.google.com', '_blank');
I actually ended up building my own Component, <Redirect>.
It takes information from the react-router element, so I can keep it in my routes. Such as:
<Route
path="/privacy-policy"
component={ Redirect }
loc="https://meetflo.zendesk.com/hc/en-us/articles/230425728-Privacy-Policies"
/>
Here is my component in case anyone is curious:
import React, { Component } from "react";
export class Redirect extends Component {
constructor( props ){
super();
this.state = { ...props };
}
componentWillMount(){
window.location = this.state.route.loc;
}
render(){
return (<section>Redirecting...</section>);
}
}
export default Redirect;
Note: This is with react-router: 3.0.5, it is not so simple in 4.x
I went through the same issue. I want my portfolio to redirect to social media handles. Earlier I used {Link} from "react-router-dom". That was redirecting to the sub directory as here,
Link can be used for routing web pages within a website. If we want to redirect to an external link then we should use an anchor tag. Like this,
Using some of the information here, I came up with the following component which you can use within your route declarations. It's compatible with React Router v4.
It's using TypeScript, but it should be fairly straightforward to convert to native JavaScript:
interface Props {
exact?: boolean;
link: string;
path: string;
sensitive?: boolean;
strict?: boolean;
}
const ExternalRedirect: React.FC<Props> = (props: Props) => {
const { link, ...routeProps } = props;
return (
<Route
{...routeProps}
render={() => {
window.location.replace(props.link);
return null;
}}
/>
);
};
And use with:
<ExternalRedirect
exact={true}
path={'/privacy-policy'}
link={'https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies'}
/>
The simplest solution is to use a render function and change the window.location.
<Route path="/goToGoogle"
render={() => window.location = "https://www.google.com"} />
If you want a small reusable component, you can just extract it like this:
const ExternalRedirect = ({ to, ...routeProps }) => {
return <Route {...routeProps} render={() => window.location = to} />;
};
and then use it (e.g. in your router switch) like this:
<Switch>
...
<ExternalRedirect exact path="/goToGoogle" to="https://www.google.com" />
</Switch>
I had luck with this:
<Route
path="/example"
component={() => {
global.window && (global.window.location.href = 'https://example.com');
return null;
}}
/>
I solved this on my own (in my web application) by adding an anchor tag and not using anything from React Router, just a plain anchor tag with a link as you can see in the picture screenshot of using anchor tag in a React app without using React Router
Basically, you are not routing your user to another page inside your app, so you must not use the internal router, but use a normal anchor.
Although this is for a non-react-native solution, but you can try.
In React Router v6, component is unavailable. Instead, now it supports element. Make a component redirecting to the external site and add it as shown.
import * as React from 'react';
import { Routes, Route } from "react-router-dom";
function App() {
return(
<Routes>
// Redirect
<Route path="/external-link" element={<External />} />
</Routes>
);
}
function External() {
window.location.href = 'https://google.com';
return null;
}
export default App;
In React Route V6 render props were removed. It should be a redirect component.
RedirectUrl:
const RedirectUrl = ({ url }) => {
useEffect(() => {
window.location.href = url;
}, [url]);
return <h5>Redirecting...</h5>;
};
Route:
<Routes>
<Route path="/redirect" element={<RedirectUrl url="https://google.com" />} />
</Routes>
I think the best solution is to just use a plain old <a> tag. Everything else seems convoluted. React Router is designed for navigation within single page applications, so using it for anything else doesn't make a whole lot of sense. Making an entire component for something that is already built into the <a> tag seems... silly?
To expand on Alan's answer, you can create a <Route/> that redirects all <Link/>'s with "to" attributes containing 'http:' or 'https:' to the correct external resource.
Below is a working example of this which can be placed directly into your <Router>.
<Route path={['/http:', '/https:']} component={props => {
window.location.replace(props.location.pathname.substr(1)) // substr(1) removes the preceding '/'
return null
}}/>
I don't think React Router provides this support. The documentation mentions
A < Redirect > sets up a redirect to another route in your application to maintain old URLs.
You could try using something like React-Redirect instead.
I was facing the same issue and solved it using by http:// or https:// in React.
Like as:
<a target="_blank" href="http://www.example.com/" title="example">See detail</a>
You can use for your dynamic URL:
<Link to={{pathname:`${link}`}}>View</Link>
For V3, although it may work for V4. Going off of Eric's answer, I needed to do a little more, like handle local development where 'http' is not present on the URL. I'm also redirecting to another application on the same server.
Added to the router file:
import RedirectOnServer from './components/RedirectOnServer';
<Route path="/somelocalpath"
component={RedirectOnServer}
target="/someexternaltargetstring like cnn.com"
/>
And the Component:
import React, { Component } from "react";
export class RedirectOnServer extends Component {
constructor(props) {
super();
// If the prefix is http or https, we add nothing
let prefix = window.location.host.startsWith("http") ? "" : "http://";
// Using host here, as I'm redirecting to another location on the same host
this.target = prefix + window.location.host + props.route.target;
}
componentDidMount() {
window.location.replace(this.target);
}
render(){
return (
<div>
<br />
<span>Redirecting to {this.target}</span>
</div>
);
}
}
export default RedirectOnServer;
I am offering an answer relevant to React Router v6 to handle dynamic routing.
I created a generic component called redirect:
export default function Redirect(params) {
window.location.replace('<Destination URL>' + "/." params.destination);
return (
<div />
)
}
I then called it in my router file:
<Route path='/wheretogo' element={<Redirect destination="wheretogo"/>}/>
import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
function App() {
return (
<Router>
<Route path="/" exact>
{window.location.replace("http://agrosys.in")}
</Route>
</Router>
);
}
export default App;
Using React with TypeScript, you get an error as the function must return a React element, not void. So I did it this way using the Route render method (and using React router v4):
redirectToHomePage = (): null => {
window.location.reload();
return null;
};
<Route exact path={'/'} render={this.redirectToHomePage} />
Where you could instead also use window.location.assign(), window.location.replace(), etc.
Complementing Víctor Daniel's answer here: Link's pathname will actually take you to an external link only when there's the 'https://' or 'http://' before the link.
You can do the following:
<Link to={{ pathname:
> "https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies"
> }} target="_blank" />
Or if your URL doesn't come with 'https://', I'd do something like:
<Link to={{pathname:`https://${link}`}} target="_blank" />
Otherwise it will prepend the current base path, as Lorenzo Demattécommented.
If you are using server-side rending, you can use StaticRouter. With your context as props and then adding <Redirect path="/somewhere" /> component in your app. The idea is every time React Router matches a redirect component it will add something into the context you passed into the static router to let you know your path matches a redirect component.
Now that you know you hit a redirect you just need to check if that’s the redirect you are looking for. then just redirect through the server. ctx.redirect('https://example/com').
You can now link to an external site using React Link by providing an object to to with the pathname key:
<Link to={ { pathname: '//example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies' } } >
If you find that you need to use JavaScript to generate the link in a callback, you can use window.location.replace() or window.location.assign().
Over using window.location.replace(), as other good answers suggest, try using window.location.assign().
window.location.replace() will replace the location history without preserving the current page.
window.location.assign() will transition to the URL specified, but will save the previous page in the browser history, allowing proper back-button functionality.
location.replace()
location.assign()
Also, if you are using a window.location = url method as mentioned in other answers, I highly suggest switching to window.location.href = url.
There is a heavy argument about it, where many users seem to adamantly want to revert the newer object type window.location to its original implementation as string merely because they can (and they egregiously attack anyone who says otherwise), but you could theoretically interrupt other library functionality accessing the window.location object.
Check out this conversation. It's terrible.
JavaScript: Setting location.href versus location
I was able to achieve a redirect in react-router-dom using the following
<Route exact path="/" component={() => <Redirect to={{ pathname: '/YourRoute' }} />} />
For my case, I was looking for a way to redirect users whenever they visit the root URL http://myapp.com to somewhere else within the app http://myapp.com/newplace. so the above helped.

How to Make hyperlink to sub domain in TypeScript Execute File

I am trying to input a link pointing to a subdomain into the navigation menu of a react theme. I am a bit embarrassed to ask the community for something that is most likely very simple. However, I've had a hard time finding any relatable examples on the web to help guide me. Below is the code and how I thought it would work, however it doesn't since it uses the current path ahead of the hyperlink.
#RouteName.ts
export enum RouteName {
Home = "/"
About = "/About"
Service = "/Service"
Portfolio = "https://sub.domain.com/"
Contact = "/Contact"
}
#Navigation.tsx
const ROUTES = [
{url: RouteName.Home, name: "Home"},
{url: RouteName.About, name: "About"},
{url: RouteName.Service, name: "Service"},
{url: RouteName.Portfolio, name: "Portfolio"},
{url: RouteName.Contact, name: "Contact"},
];
<Menu className="Menu">
{ROUTES.map((item) => (
<li key={item.url} className={pathname === item.url ? "active" : ""}>
<Link to={item.url}>{item.name}</Link>
</li>
))}
</Menu>
#App.TSX
<Routes>
<Route path={RouteName.Portfolio} element = {
<>
<TopNav />
<Portfolio />
</>
}/>
.....etc
</Routes>
Result: localhost:3000/page-currently-on/https://sub.domain.com/
Need: https://sub.domain.com/
Link is a component from react Router and is meant for links inside your website. For external links, you can use a simple <a/> tag
Portfolio
It would probably be better to create a route on /Portfolio with a redirect like so:
<Route path='/Portfolio' component={() => {
window.location.href = 'https://sub.domain.com/';
return null;
}}/>
Then, you don't have to worry about it.
export enum RouteName {
Home = "/"
About = "/About"
Service = "/Service"
Portfolio = "/Portfolio"
Contact = "/Contact"
}
This solution creates makes the website easily expandable.
You have to use pathname when you want to link to the exact URL. In your case
<Link to={{pathname: item.url}} />
I know this doesn't play well with your types so have to trial and error a bit to implement it cleanly.
Source: https://thewebdev.info/2022/03/07/how-to-add-an-external-link-with-react-router/

Dont know why I am getting to many re-render errors

Here is my code
import React, {useState} from 'react';
import Category from './Category.jsx';
function Categories() {
const [active, setActive] = useState(0);
let nameArr = [
'All',
'Life Style',
'Travel',
'Blogging',
'Hollywood Shows',
'Forest Life',
'Live Stream',
'Sports',
'Gaming',
'Data Structure',
'Css Updates',
'Google Policy',
'Avengers',
'Sublime Text 3',
'Vim',
];
nameArr = nameArr.map((name, index) => {
return (
<Category
key={index}
onClick={setActive(index)}
name={name}
active={index == active ? true : false}
/>
);
});
return (
<div className="categories">
<section className="category-section">{nameArr}</section>
</div>
);
}
export default Categories;
What i want the code to do, is to render a bunch of elements, and when you click on one, it gives the one you click on the active property, and the property from the prevous selected one
I know what the error means, i just don't understand why I am getting it in this situation
You're calling setActive immediately, when reassigning nameArr:
<Category key={index} onClick={setActive(index)}
This results in new state being set immediately, and the component re-rendering immediately.
Pass in a function that calls setActive, instead of calling setActive yourself:
<Category key={index} onClick={() => setActive(index)}
For similar reasons, the below function logs immediately, instead of waiting for a click:
window.addEventListener('click', console.log('click'));
Also consider passing the active prop regardless if you can, to be more DRY than the if/else:
const nameCategories = nameArr.map((name, index) => (
<Category key={index} onClick={setActive(index)} name={name} active={index === active} />
));

Alloy require could not find module

Problem: Trying out a simple demo for a custom tabgroup in Titanium Alloy. However, the compiler keeps failing with the message Could not find module: common. What I thought would be a straightforward test is anything but.
Titanium SDK: 3.1.3.GA
OS: iOS 7.x
controllers/index.js
var common = require('common');
function tabGroupClicked(e) {
common.tabGroupClicked(e);
}
Alloy.Globals.parent = $;
Alloy.Globals.tabGroup = $.tabGroup;
Alloy.Globals.selectedTab = $.tab1;
$.index.open();
controllers/common.js
exports.tabGroupClicked = function(e){
if (Alloy.Globals.selectedTab !== e.source){
// reset the selected tab
Alloy.Globals.previousTab = Alloy.Globals.selectedTab;
Alloy.Globals.selectedTab = e.source;
// change the selected flag
Alloy.Globals.previousTab.selected = false;
Alloy.Globals.selectedTab.selected = true;
// change the background image
Alloy.Globals.previousTab.backgroundImage = Alloy.Globals.previousTab.disabledImage;
Alloy.Globals.selectedTab.backgroundImage = Alloy.Globals.selectedTab.selectedImage;
// swapping the zindexes of the childTabs
Alloy.Globals.parent.getView(Alloy.Globals.previousTab.childTab).getView().zIndex=2;
Alloy.Globals.parent.getView(Alloy.Globals.selectedTab.childTab).getView().zIndex=3;
}
};
index.xml
<Alloy>
<Window id="index" class="container">
<View id="tabGroupWindow" zIndex="0" class="container">
<Require src="tabThreeView" id="tabThreeView"/>
<Require src="tabTwoView" id="tabTwoView"/>
<Require src="tabOneView" id="tabOneView" />
</View>
<!-- Custom tab group -->
<View id="tabGroup">
<View id="tab1" onClick="tabGroupClicked"></View>
<View id="tab2" onClick="tabGroupClicked"></View>
<View id="tab3" onClick="tabGroupClicked"></View>
</View>
</Window>
</Alloy>
Can anyone see anything that I'm obviously overlooking? I've cleaned the project, restarted Studio, scoured forums for any reference to this issue. Not finding a reference usually means I forgot some basic detail.
Your help is appreciated.
To use the require function, you have to create a service.
So the common.js module as you nammed it, has to be under this folder : app/lib. If it's not in the lib folder, it will not be recognized, and it will not be required.
You can find more help in this page.

Resources