Use 'navigation' and 'route' inside header present in class - React-navigation v5 - class

I'm stuck as I want to switch to the V5 version of react-navigation.
With v4, I used to pass my params and use them with :
Set :
this.props.navigation.navigate('MyDestination', {myParam: 'value'})
Get :
this.props.navigation.getParam('myParam')
With v5, some things changed and I now can't use the this.props.navigation since it's not seemed to be known by the app.
My code is splitted so I have my App.js that only refer to the Navigation class :
import React from 'react';
import { StyleSheet, Text, View } from 'react-native'
import Navigation from './navigation/Navigation'
export default function App() {
return (
<Navigation/>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Then my Navigation file contains all the navigation mechanism (I did not added my TabBar yet, since I want to fix the base navigation first) :
import { NavigationContainer } from '#react-navigation/native'
import { createStackNavigator } from '#react-navigation/stack'
import { createBottomTabNavigator } from 'react-navigation-tabs'
import { StyleSheet, Image } from 'react-native'
import React from 'react'
import Home from '../components/Home'
import LendList from '../components/LendList'
import AddMoney from '../components/AddMoney'
import AddStuff from '../components/AddStuff'
import Settings from '../components/Settings'
import Test from '../components/Test'
function HomeScreen() {
return(
<Home/>
)
}
function LendListScreen() {
return(
<LendList/>
)
}
const Stack = createStackNavigator()
function App() {
return(
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home"
component={Home}
options={{ title: "Home Page"}}
/>
<Stack.Screen name="LendList"
component={LendList}
options={{ title: 'Liste' }}
/>
<Stack.Screen name="AddMoney"
component={AddMoney}
options={{ title: "Ajout Money"}}
/>
<Stack.Screen name="AddStuff"
component={AddStuff}
options={{ title: "Ajout Stuff"}}
/>
<Stack.Screen name="Settings"
component={Settings}
options={{ title: "Settings"}}
/>
<Stack.Screen name="Test"
component={Test}
options={{ title: "Test"}}
/>
</Stack.Navigator>
</NavigationContainer>
)
}
export default App
And then come each of my pages (coded with classes), and here is one example, Home.js (I removed all the Style part to shorten the code displayed here) :
import React from 'react'
import { StyleSheet, Text, Image, View, Button, TouchableOpacity } from 'react-native'
import Moment from 'react-moment'
import { CommonActions } from '#react-navigation/native'
import { useNavigation } from '#react-navigation/native'
class Home extends React.Component {
static navigationOptions = () => {
return {
headerRight: () => <TouchableOpacity style={styles.settings_touchable_headerrightbutton}
onPress={() => this.goToSettings()}>
<Image style={styles.settings_image}
source={require('../assets/ic_settings.png')} />
</TouchableOpacity>
}
}
constructor(props) {
super(props)
this._goToSettings = this._goToSettings.bind(this)
}
_updateNavigationParams() {
navigation.setParams({
goToSettings: this._goToSettings
})
}
componentDidMount(){
console.log("navigation")
this._updateNavigationParams()
}
_checkMoneyDetails(navigation){
navigation.navigate('LendList', {type: 'Money'})
}
_checkStuffDetails(navigation){
navigation.navigate('LendList', {type: 'Stuff'})
}
_checkPeopleDetails(navigation){
navigation.navigate('LendList', {type: 'People'})
}
_goToSettings = () => {
navigation.navigate('Settings')
}
render(){
const date = new Date();
const { navigation } = this.props;
return(
<View style={styles.main_container}>
<View style={styles.header_view}>
<Text style={styles.header_text}>GiViToMe</Text>
<Text style={styles.header_text}>Nous sommes le :{' '}
{/* TODO: Penser à gérer ensuite les formats de date étrangers */}
<Moment element={Text} format="DD/MM/YYYY" date={date}/>
</Text>
</View>
<View style={styles.lend_view}>
<Text style={styles.title_lend_text}>Vos prêts :</Text>
<View style={styles.money_stuff_view}>
<View style={styles.money_view}>
<View style={styles.money_data_view}>
<Image source={require('../assets/ic_money.png')} style={styles.home_img} />
<Text>XXX $</Text>
</View>
<Button title='Money' onPress={() => {this._checkMoneyDetails(navigation)}}/>
</View>
<View style={styles.stuff_view}>
<View style={styles.stuff_data_view}>
<Image source={require('../assets/ic_box.png')} style={styles.home_img} />
<Text>XXX objets</Text>
</View>
<Button title='Stuff' onPress={() => {this._checkStuffDetails(navigation)}}/>
</View>
</View>
<View style={styles.people_view}>
<View style={styles.people_data_view}>
<Image source={require('../assets/ic_people.png')} style={styles.home_img} />
<Text>XXX people</Text>
</View>
<Button title='People' onPress={() => {this._checkPeopleDetails(navigation)}}/>
</View>
</View>
<View style={styles.footer_view}>
<Text style={styles.text_footer_view}>a.vescera inc.</Text>
</View>
</View>
)
}
}
export default Home
My problem is that, per the online documentation, I saw that to use "navigation" or "route" within a class, I should use the const navigation = { this.props } after the render() function.
This problem is that, to use one specific function within the header, I have to bind it after the componentDidMount() function, but the value present under render() is not yet known.
How could I solve this ? (sure that in the given example, having all the code in the navigation part allow to use navigation and route easily but you understand that I have to split my code.
Thanks.

Ok, so each time the same, I try many days solving my problem, and when I finally decide to post on stack, I find a solution :).
So, if there's some performance issue or other you may see by looking at my code, do not hesitate to correct me. I just found that this solution solved my problem.
So within my Navigation.js file, I just passed the navigation and route objects to make them usable thanks to the props into my classes, like this :
function App() {
return(
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home"
component={Home}
options={({route, navigation}) => (
{headerTitle: 'Home Page',
route: {route},
navigation: {navigation}}
)}
/>
</Stack.Navigator>
</NavigatorContainer>
)}
then within my classes I just call to this.props.navigation or this.props.route and gather form these objects what I need.
Other thing is that, for those who would use this code to build something similar, I also had to change the way I display the header button.
I do not use the static navigationOptions = () => {} anymore. I just add directly the navigation.setOptions piece of code within the ComponentDidMount function like this:
navigation.setOptions({
headerRight: () => <TouchableOpacity style={styles.settings_touchable_headerrightbutton}
onPress={() => route.params.goToSettings()}>
<Image style={styles.settings_image}
source={require('../assets/ic_settings.png')} />
</TouchableOpacity>
})
I have to do it this way since I'm using a function declared in my class, so I have to bind it in the constructor like this this._goToSettings = this._goToSettings.bind(this) and then add it to the navigation.setParams function.

When navigation.setOptions code is written inside componentDidMount add this.props before navigation and route keyword. Below is the code snippet that worked for me.
this.props.navigation.setOptions({
headerRight: () => <TouchableOpacity style={styles.settings_touchable_headerrightbutton}
onPress={() => this.props.route.params.goToSettings()}>
<Image style={styles.settings_image}
source={require('../assets/ic_settings.png')} />
</TouchableOpacity>
})

Related

Accessing Parameters in SolidJS Router

I am trying to rewrite a project I made in React in Solid. I am trying to use the Solid Router as the documentation advises.
Here are my components so far.
index.js
import { render } from 'solid-js/web'
import { Router } from '#solidjs/router'
import './index.css'
import App from './App'
render(
() => (
<Router>
<App />
</Router>
),
document.getElementById('root')
)
App.jsx
import Header from './components/Header'
import styles from './App.module.css'
import Navbar from './components/Navbar'
import Topics from './components/Topics'
function App() {
return (
<div className={styles.container}>
<Header />
<Navbar />
<Routes>
<Route path="/" element={<Articles />} />
<Route path="/:topic" component={<Topics />} />
</Routes>
</div>
)
}
export default App
Navbar.jsx
import { NavLink } from '#solidjs/router'
import { getTopics } from '../utils/api'
const Navbar = () => {
const [topics, setTopics] = createSignal([])
onMount(() => {
getTopics().then(({ topics }) => {
setTopics(topics)
})
})
return (
<nav>
<ul>
<For each={topics()}>
{topic => (
<li>
<NavLink href={`/${topic.slug}`}>{topic.slug}</NavLink>
</li>
)}
</For>
</ul>
</nav>
)
}
export default Navbar
The problem I think seems to be in the component below
Topics.jsx
import { useParams } from '#solidjs/router'
import { createSignal, For, onMount, createResource } from 'solid-js'
import { getTopicArticles } from '../utils/api'
const Topics = () => {
const { topic } = useParams()
console.log(topic)
return (
<div>
<h1>{topic}</h1>
</div>
)
}
export default Topics
The params seem to be undefined no matter what. I understand that Solid router is not exactly the same as React-Router but for this simple example I can't see where I am going wrong.
The desired outcome is to be able to click on the NavLink in the Navbar.jsx component and that routes to the desired path, for example http://localhost:3000/cooking and render the topic I need, but the params are always undefined.
This is the result of the api call, api/articles?topic=undefined
The desired result is to attach the param at the end of the api with useParams, just like in my React version
Edit: below is the Topics.jsx component updated to a working version, not sure if it is the best way.
import { useParams } from '#solidjs/router'
import { getTopicArticles } from '../utils/api'
import Article from './Article'
const Topics = () => {
const params = useParams()
const [articles, setArticles] = createSignal([])
const [loading, setLoading] = createSignal(true)
createEffect(() => {
setLoading(true)
getTopicArticles(params.topic).then(({ articles }) => {
setArticles(articles)
setLoading(false)
})
})
return (
<>
{loading() && <div>Loading...</div>}
<h2>{params.topic}</h2>
<For each={articles()}>{article => <Article article={article} />}</For>
</>
)
}
export default Topics
Could be related to the object returned from useParams is being reactive. console.log returns an empty object but destructing outputs the values as expected. That is because of the proxy and totally normal.
Retrieves a reactive, store-like object containing the current route path parameters as defined in the Route.
https://github.com/solidjs/solid-router#useparams
Also regular query parameters like ?id=1&name=John does not work with useParams, for those use useSearchParams.
import { render } from "solid-js/web";
import {
Router,
useParams,
useSearchParams,
Route,
Routes,
Link
} from "#solidjs/router";
const Home = () => {
const [params, setParams] = useSearchParams();
console.log({ ...params });
return <div>Home</div>;
};
const Blog = () => {
const params = useParams();
console.log({ ...params });
return <div>Blog {JSON.stringify(params)}</div>;
};
const App = () => {
return (
<Router>
<ul>
<li>
<Link href="/?id=1&name=john">Home</Link>
</li>
<li>
<Link href="/blog/js/1">Blog</Link>
</li>
</ul>
<Routes>
<Route path="/" component={Home} />
<Route path="/blog/:category/:id" element={Blog} />
</Routes>
</Router>
);
};
render(App, document.getElementById("app")!);
Check https://codesandbox.io/s/solid-router-demo-forked-71ef9x?file=/index.tsx for live demo.
Also, we pass component name to the component prop like so:
<Route path="/" component={Home} />

How to customize the Material UI Date Range Picker

I am using MobileDateRangePicker from "#material-ui/lab/MobileDateRangePicker". I am trying to customize it according to my needs. What I am looking for is
When the MobileDateRangePicker opens I need text input view to show first and after that when I click on calendar icon calendar view needs to come. But right now complete opposite is happening. How can I get my requirement.
This is the complete code. Any assistance would be really helpful to me. Thank you.
import * as React from "react";
import TextField from "#material-ui/core/TextField";
import AdapterDateFns from "#material-ui/lab/AdapterDateFns";
import LocalizationProvider from "#material-ui/lab/LocalizationProvider";
import Box from "#material-ui/core/Box";
import Stack from "#material-ui/core/Stack";
import MobileDateRangePicker from "#material-ui/lab/MobileDateRangePicker";
import { Button } from "#material-ui/core";
export default function ResponsiveDateRangePicker() {
const [value, setValue] = React.useState([null, null]);
const [openPicker, setOPenPicker] = React.useState(false);
const handleClick = () => {
setOPenPicker(!openPicker);
};
return (
<div>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<Stack spacing={3}>
<MobileDateRangePicker
startText="Start date"
endText="End date"
disableMaskedInput={true}
// open={openPicker}
// disableOpenPicker={true}
showDaysOutsideCurrentMonth={true}
value={value}
onChange={(newValue) => {
setValue(newValue);
}}
toolbarTitle="custom date range"
renderInput={(startProps, endProps) => (
<React.Fragment>
<TextField {...startProps} />
<Box sx={{ mx: 2 }}> to </Box>
<TextField {...endProps} />
</React.Fragment>
)}
/>
</Stack>
</LocalizationProvider>
</div>
);
}
sandbox link: https://codesandbox.io/s/responsivedaterangepicker-material-demo-forked-8qws4?file=/demo.js

Cannot find name 'RouteComponentProps'. TS2304

i just try to follow instruction to build an todo app from ionic x react documentation,
But when i try to require I got this error (view the image)
This is my code , sommeone see what i do by the wrong way ?
import { IonContent,
IonHeader,
IonPage,
IonTitle,
IonToolbar,
IonList,
IonItem,
IonCheckbox,
IonNote,
IonLabel,
IonBadge,
IonFab,
IonFabButton,
IonIcon} from '#ionic/react';
import React from 'react';
import { add } from 'ionicons/icons';
const Home: React.FC<RouteComponentProps> = (props) => {
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>Awema</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent className="ion-padding">
<IonList>
<IonItem>
<IonCheckbox slot="start" />
<IonLabel>
<h1>Create Idea</h1>
<IonNote>Run Idea by Brandy</IonNote>
</IonLabel>
<IonBadge color="success" slot="end">
5 Days
</IonBadge>
</IonItem>
</IonList>
<IonFab vertical="bottom" horizontal="end" slot="fixed">
<IonFabButton onClick={() => props.history.push('/new')}>
<IonIcon icon={add} />
</IonFabButton>
</IonFab>
</IonContent>
</IonPage>
);
};
export default Home;
Your App cannot find the RouteComponentProps. You can import them to your app:
import { RouteComponentProps } from "react-router-dom";
You need to define RouteComponentProps
For example:
type RouteComponentProps = {
className?: string,
style?: React.CSSProperties
name: string
}
export const Home: React.FC<RouteComponentProps> = // ...

How can I have a Dynamic Image uri that is not always defined in React Native?

I am trying to get the filename of my image from a fetch to my rest service. But React tries to require the image before the call has the filename so ofcourse it can't find the image and gives me a 500 error back.
Is there any way to solve or work around this?
I am trying to get the filename from a json which it gets back from the fetch.
The function in which this is supposed to happen
nextPerson = () => {
var numberOfPersons = Object.keys(this.state.peopleList).length;
if (this.state.personIndex < numberOfPersons) {
person = this.state.peopleList[this.state.personIndex]
this.setState({currentPerson:person});
this.setState({image : require('../img/' + Object(this.state.currentPerson.gebruikerFoto).url)});
this.state.personIndex++;
}
}
The render of my component
render() {
var img = this.state.image;
return (
<View style={styles.container}>
<Image style={styles.image} source={img} />
<Text style={styles.persoonNaam}>{this.state.currentPerson.gebruikerNaam}</Text>
<Text style={styles.persoonBio}>{this.state.currentPerson.biografie}</Text>
<TouchableOpacity onPress={this.likePersoon}>
<Text>Like</Text>
</TouchableOpacity>
</View>
);
}
You need to keep your component in loading state, by rendering a shimmer component (react-native-shimmer) or just use ActivityIndicator from react native, until your api call finishes. Once the data is available you can render the Image component.
render() {
if (!this.state.imageUri) return <ActivityIndicator />; // keep showing the loader until the api call is done. Update the state once the call is successful.
return (
<Image /> // your image component
)
see this example:
renderItem = ({item})=>{
return(
<TouchableOpacity onPress={ () => this._openViewPage(item.id, item.cat_id,this.state.token)} style={styles.boxContainer}>
<View style={styles.BoxLeft}>
<H1>{item.title}</H1>
<H2 style={{flexWrap: 'wrap', textAlign: 'right',}}>{item.short_description}</H2>
</View>
<View style={styles.boxRight}>
<Image source={{uri: item.image}} style={{width: 100, height: 100 }} />
</View>
</TouchableOpacity>
)
}
annd in the render of your component you can use it:
<FlatList
data= {this.state.dataSource}
renderItem={this.renderItem}
keyExtractor = { (item, index) => index.toString() }
style={{marginBottom:100}}
/>

Custom block using blockRendererFn with DraftJS

Is it possible to render a custom block where some parts of it are editable and some are not?
Here is an example of what I am trying to achieve. The ReadOnlyComponent component should be read only, while the WriteComponent contains data that can be editable.
class CustomBlock extends React.Component {
props: Props;
render() {
return (
<Layout>
<LeftColumn>
<ReadOnlyComponent>
{this.props.block.getData().get('speaker')}
</ReadOnlyComponent>
</LeftColumn>
<RightColumn>
<WriteComponent>
<EditorBlock {...this.props} />
</WriteComponent>
</RightColumn>
</Layout>
);
}
}
Here is the blockRendererFn prop that we pass to the Editor to create custom block components:
<Editor
editorState={this.state.editorState}
blockRendererFn={() => ({
component: CustomBlock,
})}
/>
setting attribute contenteditable="true" on WriteComponent should be doing what you want.
class CustomBlock extends React.Component {
...
<RightColumn>
<WriteComponent contenteditable="true">
<EditorBlock {...this.props} />
</WriteComponent>
</RightColumn>
</Layout>
);
}
}
Also you should set remaining element to be contenteditable="false". You can do this by setting attribute 'editable' for your custom block in your renderer.
<Editor
editorState={this.state.editorState}
blockRendererFn={() => ({
component: CustomBlock,
editable: false,
})}
/>
Now your custom block should be rendered as not editabable except for anything that is in WriteComponent.