Whats the proper way to propagate changes to child components? - react-native

Using react-native I don't understand, how I have to populate changes to nested structures.
I created a simple sample.
Parent owns a Button. When pressed, the clickcount within the parent will be increased.
How do I achieve that Child' clickcount will also be increased? (in my real world scenario I want specific childs to be re-rendered. I understand that I have to change some state therefore)
Parent
var React = require('react');
import { StyleSheet, Text, View, Button } from 'react-native';
import Child from './Child';
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
clickcount: this.props.clickcount,
}
child = (<Child clickcount={this.state.clickcount}/>);
}
handlePress() {
console.log('Parent handlePress');
this.increment();
}
increment() {
this.setState({clickcount: this.state.clickcount+1});
}
render() {
return (
<View>
<Text>Parent {this.state.clickcount}</Text>
<Button
title="OK"
onPress={() => this.handlePress()}
/>
</View>
);
}
}
export default Parent;
Child
var React = require('react');
import { StyleSheet, Text, View, Button } from 'react-native';
class Child extends React.Component {
constructor(props) {
super(props);
this.state = {
clickcount: this.props.clickcount,
}
}
handlePress() {
console.log('Child handlePress');
this.increment();
}
increment() {
this.setState({clickcount: this.state.clickcount+1});
}
render() {
return (
<View>
<Text>Child {this.state.clickcount}</Text>
</View>
);
}
}
export default Child;
Currently, after 3x click the output looks like:
Parent 3
Child 0

You can pass the increment function to the child so the parent owns the click count
class Child extends React.Component {
render() {
return (
<div>
<button onClick={this.props.increment}/>
{this.props.clickCount}
</div>
)
}
}
class Parent extends React.Component {
state = {
clickCount: 0
}
increment = () => {
this.setState({ clickCount: this.state.clickCount + 1 })
}
render () {
return (
<Child increment={() => this.increment()} clickCount={this.state.clickCount}/>
)
}
}

Related

Class To Function Component

I am very new to react native. The app I am developing has functional components.
Is there any way to convert class component to function component or convert this class into a function?
Is it possible to use functional and class component both in single app?
import React from 'react';
import DayPicker, { DateUtils } from 'react-day-picker';
import 'react-day-picker/lib/style.css';
export default class Example extends React.Component {
constructor(props) {
super(props);
this.handleDayClick = this.handleDayClick.bind(this);
this.state = {
selectedDays: [],
};
}
handleDayClick(day, { selected }) {
const { selectedDays } = this.state;
if (selected) {
const selectedIndex = selectedDays.findIndex(selectedDay =>
DateUtils.isSameDay(selectedDay, day)
);
selectedDays.splice(selectedIndex, 1);
} else {
selectedDays.push(day);
}
this.setState({ selectedDays });
}
render() {
return (
<div>
<DayPicker
selectedDays={this.state.selectedDays}
onDayClick={this.handleDayClick}
/>
</div>
);
}
}
Yes you can use both functional and class component in same time
import React, {useState} from "react";
import DayPicker, { DateUtils } from 'react-day-picker';
import 'react-day-picker/lib/style.css';
export default function Example(props = {}) {
// read about useState hooks, it replace state
const [selectedDays, setSelectedDays] = useState([]);
handleDayClick(day, { selected }) {
if (selected) {
const selectedIndex = selectedDays.findIndex(selectedDay =>
DateUtils.isSameDay(selectedDay, day)
);
selectedDays.splice(selectedIndex, 1);
} else {
selectedDays.push(day);
}
setSelectedDays( selectedDays );
}
render() {
return (
<div>
<DayPicker
selectedDays={ selectedDays}
onDayClick={handleDayClick}
/>
</div>
);
}
}

How to pass a prop to match up with a state property in child in react-native

In my application, I created a timer component. This is a smart component because I wanted to handle the counter state inside the component.
this is my code
import React, { Component } from "react";
import {
View,
Text,
StyleSheet
} from "react-native";
import { RoundedButton} from "../../mixing/UI";
class Timer extends Component {
constructor(props) {
super(props);
this.state = {
counter: 30
}
this.interval = null;
}
componentWillUnmount() {
cleanUp();
}
cleanUp = () => {
clearInterval(this.interval);
}
decreaseCounter = () => {
if (this.state.counter === 0) {
return this.cleanUp();
}
this.setState({counter: this.state.counter - 1});
}
startCounter = () => {
this.interval = setInterval(this.decreaseCounter, 1000);
}
render() {
return (
<View>
<RoundedButton text='Log in' onPress={() => this.startCounter()} />
<Text>{this.state.counter}</Text>
<RoundedButton text='Log in' onPress={() => this.cleanUp()} />
</View>
);
}
}
// styles
const styles = StyleSheet.create({
});
export default Timer;
Now I want to call this from my parent screen. If I pass the counter as a prop,
Now the counter state can't be handled from Timer component. How can I handle the state of the child based on the parent prop.
you can use react component lifecycle componentDidMount()
componentDidMount(){
this.setState({counter: this.props.counter});
}
There after you can use this.setState({counter: this.state.counter - 1})

React-Native: How to nest containers

How can I construct container from another containers.
for example:
containerA - responsible for A
containerB - responsible for B
Container C - responsible for A + B with different Style C.
in code:
class ContainerA extends Component{
render() {
return (
<ComponentA/>
)
}
}
class ContainerB extends Component{
render() {
return (
<ComponentB/>
)
}
}
class ContainerC extends Component{
render() {
return (
<ContainerA/>
<ContainerB/>
)
}
}
When you want to group components in React Native, you can use View as such
import React, { Component } from 'react'
import { View } from 'react-native'
import ContainerA from './ContainerA'
import ContainerB from './ContainerB'
class ContainerC extends Component{
render() {
return (
<View style={styles.containerStyle}>
<ContainerA/>
<ContainerB/>
</View>
)
}
}
const styles = {
containerStyle = {
// ...
}
}

react native pass props to another component

I've been struggling passing a value from one component to another. It's a continuation of the issue from a previous question which was partially resolved: react-native tab navigator search box
I'm using tab navigator and here's my app setup:
index.js (renders tab setup)
  router.js
     searchHeader.js
     tab1.js
     tab2.js
     etc
In index.js when a tab is changed I'm getting the name of the tab. I want to pass that to searchHeader.js to update the placeholder text.
As searchHeader.js isn't imported into index.js and not a direct child how do I pass it that value?
index.js
import React, { Component } from 'react';
import { Root, Tabs } from './config/router';
import { Alert,View } from 'react-native';
class App extends Component {
constructor(props) {
super(props);
this.state = {
searchText: '',
}
}
_getCurrentRouteName(navState) {
if (navState.hasOwnProperty('index')) {
this._getCurrentRouteName(navState.routes[navState.index])
} else {
if (navState.routeName==='One') {
this.setState({searchText:'Search One'})
}
if (navState.routeName==='Two') {
this.setState({searchText:'Search Two'})
}
if (navState.routeName==='Three') {
this.setState({searchText:'Search Three'})
}
if (navState.routeName==='Four') {
this.setState({searchText:'Search Four'})
}
}
}
render() {
return (
<Root onNavigationStateChange={(prevState, newState) => {
this._getCurrentRouteName(newState)
}} />
)
}
}
export default App;
router.js
...
export const Root = StackNavigator({
Tabs: {
screen: Tabs,
navigationOptions: {
header: <SearchHeader data={'Test'} />
}
},
}, {
mode: 'modal',
});
searchHeader.js
import React, { Component } from 'react';
import { View,Text,Dimensions,Alert } from 'react-native';
import { SearchBar } from 'react-native-elements';
class SearchHeader extends Component {
constructor(props) {
super(props);
this.state = {
placeholder: "Search One"
}
}
render() {
return (
<SearchBar
noIcon
containerStyle={{backgroundColor:'#fff'}}
inputStyle={{backgroundColor:'#e3e3e3',}}
lightTheme = {true}
round = {true}
placeholder={data}
placeholderTextColor = '#000'
/>
);
}
};
export default SearchHeader;
You could perhaps pass it as a navigation prop using the setParams method.
An alternative, depending on the scope of your app, would be to look at a state library such as Redux or MobX - but if it's a small app, it's overkill
For that you can use Redux, you will have a store where you can put shared properties and values,
Then your components can connect to that store and bind its props with the chosen reducer(s) and dispatch actions..
this structure may work:
class Home extends Component {
func(val) {
this.setState({value: val});
}
render() {
return (
<View>
<Two func={(val) => this.func(val)} />
</View>
)
}
}
class Two extends Component {
render() {
return (
<View>
<Button title="set" onPress={() => this.props.func('data')} />
</View>
)
}
}

Call child function from parent component in React Native

I'm developing my first React Native app. What I'm trying to achieve is to execute a child function from the parent component, this is the situation:
Child
export default class Child extends Component {
...
myfunct: function() {
console.log('Managed!');
}
...
render(){
return(
<Listview
...
/>
);
}
}
Parent
export default class Parent extends Component {
...
execChildFunct: function() {
...
//launch child function "myfunct"
...
//do other stuff
}
render(){
return(
<View>
<Button onPress={this.execChildFunct} />
<Child {...this.props} />
</View>);
}
}
In this example, I would like to log 'Managed!' when I press the button in the parent class. How is it feasible?
Nader Dabit's answer is outdated, since using String literals in ref attributes has been deprecated. This is how we would do it as of September 2017:
<Child ref={child => {this.child = child}} {...this.props} />
<Button onPress={this.child.myfunc} />
Same functionality, but instead of using a String to reference the component, we store it in a global variable instead.
Here's how you can do this with functional components:
Parent
Use useRef() to give the child component a reference in the parent:
const childRef = useRef()
// ...
return (
<ChildComponent ref={childRef} />
)
...
Child
Pass ref as one of the constructor parameters:
const ChildComponent = (props, ref) => {
// ...
}
Import useImperativeHandle and forwardRef methods from the 'react' library:
import React, { useImperativeHandle, forwardRef } from 'react'
Use useImperativeHandle to bind functions to the ref object, which will make these functions accessible to the parent
These methods won't be internally available, so you may want to use them to call internal methods.
const ChildComponent = (props, ref) => {
//...
useImperativeHandle(ref, () => ({
// each key is connected to `ref` as a method name
// they can execute code directly, or call a local method
method1: () => { localMethod1() },
method2: () => { console.log("Remote method 2 executed") }
}))
//...
// These are local methods, they are not seen by `ref`,
const localMethod1 = () => {
console.log("Method 1 executed")
}
// ..
}
Export the child component using forwardRef:
const ChildComponent = (props, ref) => {
// ...
}
export default forwardRef(ChildComponent)
Putting it all together
Child Component
import React, { useImperativeHandle, forwardRef } from 'react';
import { View } from 'react-native'
const ChildComponent = (props, ref) => {
useImperativeHandle(ref, () => ({
// methods connected to `ref`
sayHi: () => { sayHi() }
}))
// internal method
const sayHi = () => {
console.log("Hello")
}
return (
<View />
);
}
export default forwardRef(ChildComponent)
Parent Component
import React, { useRef } from 'react';
import { Button, View } from 'react-native';
import ChildComponent from './components/ChildComponent';
const App = () => {
const childRef = useRef()
return (
<View>
<ChildComponent ref={childRef} />
<Button
onPress={() => {
childRef.current.sayHi()
}}
title="Execute Child Method"
/>
</View>
)
}
export default App
There is an interactive demo of this on Expo Snacks:
https://snack.expo.dev/#backupbrain/calling-functions-from-other-components
This explanation is modified from this TutorialsPoint article
You can add a ref to the child component:
<Child ref='child' {...this.props} />
Then call the method on the child like this:
<Button onPress={this.refs.child.myfunc} />
it is in react. i hope it may help you.
class Child extends React.Component {
componentDidMount() {
this.props.onRef(this)
}
componentWillUnmount() {
this.props.onRef(null)
}
method() {
console.log('do stuff')
}
render() {
return <h1>Hello World!</h1>
}
}
class EnhancedChild extends React.Component {
render() {
return <Child {...this.props} />
}
}
class Parent extends React.Component {
onClick = () => {
this.child.method() // do stuff
};
render() {
return (
<div>
<EnhancedChild onRef={ref => (this.child = ref)} />
<button onClick={this.onClick}>Child.method()</button>
</div>
);
}
}
ReactDOM.render(<Parent />, document.getElementById('root'))
Original Solution:
https://jsfiddle.net/frenzzy/z9c46qtv/
https://github.com/kriasoft/react-starter-kit/issues/909
Simple and easy way to Parent --> Child function call
/* Parent.js */
import React, { Component } from "react";
import { TouchableOpacity, Text } from "react-native";
import Child from "./Child";
class Parent extends React.Component {
onChildClick = () => {
this.child.childFunction(); // do stuff
};
render() {
return (
<div>
<Child onRef={(ref) => (this.child = ref)} />
<TouchableOpacity onClick={this.onChildClick}>
<Text>Child</Text>
</TouchableOpacity>
</div>
);
}
}
/* Child.js */
import React, { Component } from "react";
class Child extends React.Component {
componentDidMount() {
this.props.onRef(this);
}
componentWillUnmount() {
this.props.onRef(undefined);
}
childFunction() {
// do stuff
alert("childFunction called");
}
render() {
return <View>Hello World!</View>;
}
}
Original Solution:
https://github.com/kriasoft/react-starter-kit/issues/909
I think you have misunderstood something about component structure.
Assume that your child is a component which generates button for your other components. In this hierarchy your child has to inform it's parent that it was pressed.
child -----> parent
export default class Child extends Component {
return(
<Button onPress={this.props.onPress } />
);
}
In your parent component use child component to generate a button for you. In this way you can use child component any other components as a independent button.
export default class Parent extends Component {
constructor(props) {
super(props);
this.execChildFunct=this.execChildFunct.bind(this)
}
execChildFunct: function() {
console.log('Managed!');
}
return (
<Child onPress = {this.execChildFunct}></Child>
)
}