How can I use parent's callback in children component? - react-native

Sorry. I'm new to react native and react.
And I just encountered setCount is not a function. (In 'setCount(1)','setCount' is undefined) error.
How can I use setCount Method in AComponent?
import React, {useState} from 'react';
import {
Text,
} from 'react-native';
const AComponent = ({count, callback}) => {
callback(1);
return <Text>{count}</Text>;
};
const App = () => {
const [count, setCount] = useState(0);
return <AComponent count={count} callback={setCount} />;
};
const styles = StyleSheet.create({
container: {},
});
export default App;

You are renaming your function to callback.
So in your component you need to use callback instead of setCount, or rename your props callback to setCount (preferable):
return <AComponent count={count} setCount={setCount} />
Each key={value} defined when you use your component, can be accessed with the key in the component.
I suggest you to have a deep read of the following article: https://reactjs.org/docs/components-and-props.html

Related

I want to render a specific static object in react native

I try to render a specific object inside a component (static object) in react native,after i get it with http request from axios API .The (node)server works fine but whenever i try to render it on the screen nothing shows.
Also when i console.log the object its correct(on client side too) but still nothing on simulator screen.
I dont know if i do something wrong or i need hooks for that(im new in react native so excuse me if i open again some same question) .
The code is below :
Client
import React, { Component,
useEffect,
useState } from 'react';
import {
StyleSheet,
Text,
View ,
} from 'react-native';
import axios from 'axios';
var res;
export default function App() {
axios.get('http://x.x.x.x:x/rec')
.then
(function (response){
console.log(response.data);
res = response.data;
})
return (
<View style = {styles.container}>
<Text>This car is a : {res}</Text>
</View>
)};
const styles = StyleSheet.create({
container: {
flex: 1 ,
marginTop:100,
},
});
Server
const app = require('express')();
const { json } = require('body-parser');
const car = {
type: "Fiat",
model : "500"
};
const myCar = JSON.stringify(car);
app.get("/rec",(req,res) => {
res.send(myCar);
console.log("Took Car");
})
app.get("/",(req,res) => {
res.set('Content-Type', 'text/plain');
res.send("You have done it ");
console.log("Took /");
})
var listener = app.listen(8888,()=>{
console.log(listener.address().port);
});
Better to use hook for it
import React, { Component, useEffect, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import axios from 'axios';
export default function App() {
const [label, setLabel] = useState('')
axios.get('http://x.x.x.x:x/rec')
.then((response) => {
const data = response.data
const resultLabel = typeof data === 'string' ? data :
`${data.type} ${data.model}`
setLabel(`This car is a : ${resultLabel}`)
})
return (
<View style = {styles.container}>
<Text>{label}</Text>
</View>
)};
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop:100,
},
});

Context returns undefined

My context returns undefined so I cannot get the name value from provider.
I made a snack at https://snack.expo.io/#johanmelin/functional-context
The code looks like
import React from 'react';
import { Text } from 'react-native';
const DataContext = React.createContext();
const DataProvider = props => {
const [name, setName] = React.useState("John");
return (
<DataContext.Provider value={name}>
{props.children}
</DataContext.Provider>
)
}
function App (props) {
const data = React.useContext(DataContext);
return (
<DataProvider>
<Text>hi {data.name}</Text>
</DataProvider>
)
}
export default App;
Can anyone see what I'm missing?
Provider needs to be setup before consumer. In your code, App gets render first, so you are trying to use the context before the provider is setup.
so your code should be something like this:
import React from 'react';
import { Text } from 'react-native';
const DataContext = React.createContext();
const DataProvider = props => {
const data = React.useContext(DataContext);
return (
<Text>
{data.value}
</Text>
)
}
function App () {
const [name, setName] = React.useState("John");
return (
<DataContext.Provider value={name}>
<DataProvider />
</DataContext.Provider>
)
}
export default App;

Redux: mapStateToProps is not being called

I understand this kind of question was already asked several times here at StackOverflow. But I tried all the recommended solutions and nothing works for me. I'm running out of ideas.
The problem is with a React Native application for Android. Basically, the app provides a search bar to search an underlying database. The search results should be put into the store.
I use Redux v4.0.5, React-Redux v7.1.3, React v16.12.0 and React Native v0.61.5. For debugging, I use React Native Debugger in the latest version.
Now the simplified code. First, the component with the search bar. Here, mapStateToProps() is called. User makes an input and useEffect() immediately runs the database query, which should result in immediately calling mapStateToProps().
import React, {useEffect, useRef, useState} from 'react';
import {connect} from 'react-redux';
import {RootState} from '../../../rootReducer/rootReducer';
import {setResultValueSearchBar} from '../../../store/searchBar/actions';
imports ...
type Props = {};
const SearchBar: React.FC<Props> = () => {
const [returnValue, setReturnValue] = useState('');
const [inputValue, setInputValue] = useState('');
useEffect(() => {
// get query results
// logic to finally get a result string that should be put into the store
const resultNames: string = resultNamesArray.toString();
// method to set local and Redux state
const sendReturnValueToReduxStore = (resultNames: string) => {
setReturnValue(resultNames);
setResultValueSearchBar({resultValue: resultNames});
console.log('result value sent to store ', resultNames);
};
// call above method
sendReturnValueToReduxStore(resultNames);
}, [inputValue, returnValue]);
return (
<View>
<ScrollView>
<Header searchBar>
<Item>
<Input
placeholder="Search"
onChangeText={text => setInputValue(text)}
value={inputValue}
/>
</Item>
</Header>
</ScrollView>
</View>
);
};
function mapStateToProps(state: RootState) {
console.log("map state to props!", state); // is only called one time, initially
return {
resultValue: state.searchBarResult.resultValue,
};
}
const mapDispatchToProps = {
setResultValueSearchBar,
};
export default connect(mapStateToProps, mapDispatchToProps)(SearchBar);
Here is the rootReducer:
import {combineReducers} from 'redux';
import searchBarResultReducer from '../store/searchBar/reducers';
import reducer2 from '../store/reducer2example/reducers';
const rootReducer = combineReducers({
searchBarResult: searchBarResultReducer,
reducer2Result: reducer2,
});
export type RootState = ReturnType<typeof rootReducer>;
Here is the searchBarResultReducer in reducers.ts file:
import {
SearchBarResultState,
SET_RESULT_VALUE_SEARCHBAR,
ResultValueType,
} from './types';
const initialState: SearchBarResultState = {
resultValue: 'No results',
};
// take state and action and then return a new state
function searchBarResultReducer(
state = initialState,
action: ResultValueType,
): SearchBarResultState {
console.log('invoked result: ', action.type); // called only initially
if (action.type === 'SET_RESULT_VALUE_SEARCHBAR') {
return {
...state,
...action.payload,
};
} else {
return state;
}
}
export default searchBarResultReducer;
And the corresponding types.ts ...
export const SET_RESULT_VALUE_SEARCHBAR = 'SET_RESULT_VALUE_SEARCHBAR';
export interface SearchBarResultState {
resultValue: string;
}
interface ResultValueAction {
type: typeof SET_RESULT_VALUE_SEARCHBAR;
payload: SearchBarResultState;
}
export type ResultValueType = ResultValueAction
... and the actions.ts:
import {SET_RESULT_VALUE_SEARCHBAR, ResultValueType, SearchBarResultState} from './types'
export const setResultValueSearchBar = (resultValue: SearchBarResultState): ResultValueType => ({
type: SET_RESULT_VALUE_SEARCHBAR,
payload: resultValue,
});
And index.js:
import React from 'react';
import {AppRegistry} from 'react-native';
import {createStore, applyMiddleware, compose} from 'redux';
import {Provider} from 'react-redux';
import App from './App';
import {name as appName} from './app.json';
import rootReducer from './src/rootReducer/rootReducer';
import Realm from 'realm';
import { composeWithDevTools } from 'redux-devtools-extension';
import invariant from 'redux-immutable-state-invariant';
const composeEnhancers = composeWithDevTools({});
const store = createStore(
rootReducer,
composeEnhancers(applyMiddleware(invariant()))
);
const Root = () => {
Realm.copyBundledRealmFiles();
return (
<Provider store={store}>
<App />
</Provider>
);
};
AppRegistry.registerComponent(appName, () => Root);
To summarize: Whenever the database query succeeds, the result value should be sent to the store. But in the React Native Debugger/Redux Devtools, the reducer/mapStateToProps() is called only once and only, as shown by the console.log s in the code.
What is going on here?
Solved! As stated by Hemant in this Thread, you also have to pass the action that you import as props into the component. Works like a charm now :)

How to listen to route changes in react router v4?

I have a couple of buttons that acts as routes. Everytime the route is changed, I want to make sure the button that is active changes.
Is there a way to listen to route changes in react router v4?
I use withRouter to get the location prop. When the component is updated because of a new route, I check if the value changed:
#withRouter
class App extends React.Component {
static propTypes = {
location: React.PropTypes.object.isRequired
}
// ...
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) {
this.onRouteChanged();
}
}
onRouteChanged() {
console.log("ROUTE CHANGED");
}
// ...
render(){
return <Switch>
<Route path="/" exact component={HomePage} />
<Route path="/checkout" component={CheckoutPage} />
<Route path="/success" component={SuccessPage} />
// ...
<Route component={NotFound} />
</Switch>
}
}
To expand on the above, you will need to get at the history object. If you are using BrowserRouter, you can import withRouter and wrap your component with a higher-order component (HoC) in order to have access via props to the history object's properties and functions.
import { withRouter } from 'react-router-dom';
const myComponent = ({ history }) => {
history.listen((location, action) => {
// location is an object like window.location
console.log(action, location.pathname, location.state)
});
return <div>...</div>;
};
export default withRouter(myComponent);
The only thing to be aware of is that withRouter and most other ways to access the history seem to pollute the props as they de-structure the object into it.
As others have said, this has been superseded by the hooks exposed by react router and it has a memory leak. If you are registering listeners in a functional component you should be doing so via useEffect and unregistering them in the return of that function.
v5.1 introduces the useful hook useLocation
https://reacttraining.com/blog/react-router-v5-1/#uselocation
import { Switch, useLocation } from 'react-router-dom'
function usePageViews() {
let location = useLocation()
useEffect(
() => {
ga.send(['pageview', location.pathname])
},
[location]
)
}
function App() {
usePageViews()
return <Switch>{/* your routes here */}</Switch>
}
You should to use history v4 lib.
Example from there
history.listen((location, action) => {
console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
console.log(`The last navigation action was ${action}`)
})
withRouter, history.listen, and useEffect (React Hooks) works quite nicely together:
import React, { useEffect } from 'react'
import { withRouter } from 'react-router-dom'
const Component = ({ history }) => {
useEffect(() => history.listen(() => {
// do something on route change
// for my example, close a drawer
}), [])
//...
}
export default withRouter(Component)
The listener callback will fire any time a route is changed, and the return for history.listen is a shutdown handler that plays nicely with useEffect.
import React, { useEffect } from 'react';
import { useLocation } from 'react-router';
function MyApp() {
const location = useLocation();
useEffect(() => {
console.log('route has been changed');
...your code
},[location.pathname]);
}
with hooks
With hooks:
import { useEffect } from 'react'
import { withRouter } from 'react-router-dom'
import { history as historyShape } from 'react-router-prop-types'
const DebugHistory = ({ history }) => {
useEffect(() => {
console.log('> Router', history.action, history.location)
}, [history.location.key])
return null
}
DebugHistory.propTypes = { history: historyShape }
export default withRouter(DebugHistory)
Import and render as <DebugHistory> component
import { useHistory } from 'react-router-dom';
const Scroll = () => {
const history = useHistory();
useEffect(() => {
window.scrollTo(0, 0);
}, [history.location.pathname]);
return null;
}
With react Hooks, I am using useEffect
import React from 'react'
const history = useHistory()
const queryString = require('query-string')
const parsed = queryString.parse(location.search)
const [search, setSearch] = useState(parsed.search ? parsed.search : '')
useEffect(() => {
const parsedSearch = parsed.search ? parsed.search : ''
if (parsedSearch !== search) {
// do some action! The route Changed!
}
}, [location.search])
in this example, Im scrolling up when the route change:
import React from 'react'
import { useLocation } from 'react-router-dom'
const ScrollToTop = () => {
const location = useLocation()
React.useEffect(() => {
window.scrollTo(0, 0)
}, [location.key])
return null
}
export default ScrollToTop
In some cases you might use render attribute instead of component, in this way:
class App extends React.Component {
constructor (props) {
super(props);
}
onRouteChange (pageId) {
console.log(pageId);
}
render () {
return <Switch>
<Route path="/" exact render={(props) => {
this.onRouteChange('home');
return <HomePage {...props} />;
}} />
<Route path="/checkout" exact render={(props) => {
this.onRouteChange('checkout');
return <CheckoutPage {...props} />;
}} />
</Switch>
}
}
Notice that if you change state in onRouteChange method, this could cause 'Maximum update depth exceeded' error.
For functional components try useEffect with props.location.
import React, {useEffect} from 'react';
const SampleComponent = (props) => {
useEffect(() => {
console.log(props.location);
}, [props.location]);
}
export default SampleComponent;
For React Router v6 & React Hooks,
You need to use useLocation instead of useHistory as it is deprecated
import { useLocation } from 'react-router-dom'
import { useEffect } from 'react'
export default function Component() {
const history = useLocation();
useEffect(() => {
console.log('> Router', history.pathname)
}, [history.pathname]);
}
With the useEffect hook it's possible to detect route changes without adding a listener.
import React, { useEffect } from 'react';
import { Switch, Route, withRouter } from 'react-router-dom';
import Main from './Main';
import Blog from './Blog';
const App = ({history}) => {
useEffect( () => {
// When route changes, history.location.pathname changes as well
// And the code will execute after this line
}, [history.location.pathname]);
return (<Switch>
<Route exact path = '/' component = {Main}/>
<Route exact path = '/blog' component = {Blog}/>
</Switch>);
}
export default withRouter(App);
I just dealt with this problem, so I'll add my solution as a supplement on other answers given.
The problem here is that useEffect doesn't really work as you would want it to, since the call only gets triggered after the first render so there is an unwanted delay.
If you use some state manager like redux, chances are that you will get a flicker on the screen because of lingering state in the store.
What you really want is to use useLayoutEffect since this gets triggered immediately.
So I wrote a small utility function that I put in the same directory as my router:
export const callApis = (fn, path) => {
useLayoutEffect(() => {
fn();
}, [path]);
};
Which I call from within the component HOC like this:
callApis(() => getTopicById({topicId}), path);
path is the prop that gets passed in the match object when using withRouter.
I'm not really in favour of listening / unlistening manually on history.
That's just imo.

Is there an optimal way to write dynamic component switching in React?

When writing components for a layout that needs to be switched dynamically via data from the backend, I often find myself writing React components that look like this:
import React from 'react';
import TextInput from './TextInput';
import DateInput from './DateInput';
const Input = (props) => {
const {
type,
...otherProps
} = props;
switch (type) {
case 'text':
return <TextInput {...otherProps} />;
case 'date':
return <DateInput {...otherProps} />;
// etc…
default:
return null;
}
};
export default Input;
Which leads to the list of imports ballooning when the types are expanded upon.
Is there any alternative method for dynamic component switching that would be more optimal/performant/reliable than this one?
How about this:
import React from 'react';
import TextInput from './TextInput';
import DateInput from './DateInput';
const TYPES = {
text: TextInput,
date: DateInput,
};
const Input = (props) => {
const {
type,
...otherProps
} = props;
const Component = TYPES[type];
if (!Component) return null;
return <Component {...otherProps} />;
};
export default Input;
Generally you want to enumerate the possible options somewhere, and an object lookup is an easy way to do it. Dynamic require calls that other answers have mentioned are generally a little questionable because tools cannot analyse the dependencies, and it means you're API is much harder to understand.
If you use a build tool such as webpack dynamic requires are supported, which allows you to do something like the following:
import React from 'react';
const typeMap = {
text: 'TextInput',
date: 'DateInput'
};
const Input = (props) => {
const {
type,
...otherProps
} = props;
const typeInput = typeMap[type];
if (!typeInput) return null;
const InputComponent = require(`./${typeInput}`);
return <InputComponent { ...otherProps } />;
};
export default Input;
You can use require to dynamically load modules. However you have to define somewhere what is the component module path. For example:
const components = {
text: 'TextInput',
date: 'DateInput',
};
const Input = (props) => {
const { type, ...otherProps } = props;
const Component = require('./' + components[type]);
return type ? <Component {...otherProps} /> : null;
};