React Native: Move component in view hierarchy - react-native

How can a component be moved from one part of the render hierarchy to another while maintaining component state? In the example below, the result of the call to setView creates a new view (as seen by a new instanceValue number), even though I pass what looks like the existing view.
class TestTo extends React.Component {
constructor(props) {
super(props);
this.state = {
instanceValue: parseInt(Math.random() * 100)
}
}
render() {
return <Text>{this.state.instanceValue}</Text>
}
}
class TestFrom extends React.Component {
constructor(props) {
super(props);
this.state = {
view: <TestTo />
}
}
doSet = () => {
this.props.nav.setView(this.state.view);
}
render() {
return <View>
<Button title="doaction" onPress={this.doSet} />
{this.state.view}
</View>
}
}
class Holder extends React.Component {
constructor(props) {
super(props);
this.state = {
view: <TestFrom nav={this} />
}
}
setView = (view) => {
this.setState({view: view});
}
render() {
return this.state.view
}
}
<Holder />

Related

Whats the proper way to propagate changes to child components?

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}/>
)
}
}

React Native | Get Switch Value from another Component

I would like to get the value of the switch inside ToggleCampus from Map.js. How can I update the value of the state inside Map.js from ToggleCampus.js?
Map.js
export default class Map extends React.Component{
constructor(props) {
super(props);
this.state = { switchVal: true};
}
render(){
return (
<ToggleCampus switchVal = {this.state.switchVal} />
);
}
}
ToggleCampus.js
export default class ToggleCampus extends React.Component {
constructor(props){
super(props);
}
render() {
console.log(this.props.switchVal);
return(
<Switch
value={this.props.switchVal}
*(not sure how to use onChange here)*
/>
);
}
}
So basically what you have to do is pass the function as props to ToggleCampus to update the switchVal. Like suppose in ToggleCampus you want to change the value on button click, so check the below method:
Map.js
export default class Map extends React.Component{
constructor(props) {
super(props);
this.state = { switchVal: true};
}
changeSwitch = (value) => {
this.setState({switchVal:value});
}
render(){
return (
<ToggleCampus changeSwitch={this.changeSwitch} switchVal = {this.state.switchVal} /> // passed changeSwitch
);
}
}
and in togglecampus.js
export default class ToggleCampus extends React.Component {
constructor(props){
super(props);
}
render() {
console.log(this.props.switchVal);
return(
<>
<Switch
value={this.props.switchVal}
*(not sure how to use onChange here)*
/>
<Button title="click" onPress={() => this.props.changeSwitch(false)} /> // added this
</>
);
}
}
hope it helps.

Children calling grandparent function

I have a box containing a list. The list is made of todoItems. A delete button is next to each item. The button should call the delete method of the box class. Should I pass it to the class List first? Can I call directly the method in the class Box?
class TodoItem extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(e)
{
const todoItemId = this.props.todoItemId;
if (!todoItemId)
{
return;
}
this.props.onTodoItemDeleteList({ todoItemId: todoItemId });
}
render() {
return (
<div className="todoItem">
<button onClick={() => this.handleClick()}>delete</button>;
</div>
);
}
}
My List: here the onTodoItemDeleteList is seen in the console, but appears as undefined.
class TodoItemList extends React.Component {
constructor(props) {
super(props);
this.handleItemDeleteList = this.handleItemDeleteList.bind(this);
}
handleItemDeleteList(todoItemId)
{
//call handleItemDelete
}
render() {
if (this.props.data)
{
var todoItemNodes = this.props.data.map(function (todoItem){
return (
<TodoItem todoItemId={todoItem.todoItemId} onTodoItemDeleteList={this.handleItemDeleteList} key={todoItem.todoItemId}>
</TodoItem>
);
});
}
return <div className="todoItemList">{todoItemNodes}</div>;
}
}
My Box: this is where I handle my ajax call to the server.
class TodoItemBox extends React.Component {
constructor(props) {
super(props);
this.state = { data: [] };
this.handleItemDelete = this.handleItemDelete.bind(this);
}
handleItemDelete(todoItemId) {
const data = new FormData();
data.append('todoItemId', todoItemId);
const xhr = new XMLHttpRequest();
xhr.open('post', this.props.deleteUrl, true);
xhr.onload = () => this.loadTodoItemsFromServer();
xhr.send(data);
}
render() {
return (
<div className="todoItemBox">
<TodoItemList data={this.state.data} />
</div>
);
}
}
I solved it by using arrow function in the parent too, it looks like this:
onTodoItemDeleteList={ (todoItemId) => handleItemDeleteList(todoItemId)}
and in the constructor:
handleItemDeleteList = this.handleItemDeleteList.bind(this);

Assign to `this.state` directly or define a `state = {};` class property with the desired state in the Dashboard component

I'm passing a string value from one component class to another and try to update the state in another class
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
systemDetailsData: null,
}
}
CalledFromHeader = (systemDetailsData11) => {
this.setState({ systemDetailsData:systemDetailsData11 })
}
}
class Header extends Component {
constructor(props) {
super(props);
Dashboard_Obj = new Dashboard();
}
OnPress = () => {
Dashboard_Obj.CalledFromHeader("system data");
}
}
I'm getting this error ---> Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state directly or define a state = {}; class property with the desired state in the Dashboard component.
I want to update the state in Dashboard class using above code, Can anyone help me how to achieve this?
Call the Header component in Dashboard render method and pass a function as a prop to Header component.
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
systemDetailsData: null,
}
}
CalledFromHeader = (systemDetailsData11) => {
this.setState({ systemDetailsData:systemDetailsData11 })
}
redner(){
return <Header changeState={this.CalledFromheader} />
}
}
class Header extends Component {
constructor(props) {
super(props);
}
render(){
return(
// something view onPress handler
<Button onPress={()=>{
this.props.CalledFromHeader('Some parameters')
}} />
)
}
}

React Native - can I set dynamic initial state?

let say I have a state like this:
constructor(props) {
super(props);
this.state = {
FirstTime:
{
foo: 'ex1'
}
}
}
and then I setState the FirstTime to add another key/value:
this.setState({FirstTime: {...this.state.FirstTime, bar: 'ex2'}})
there's a way to change the initial state to be like this:
constructor(props) {
super(props);
this.state = {
FirstTime:
{
foo: 'ex1',
bar: 'ex2'
}
}
}
when I reloaded the apps?
Try something like this
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
FirstTime: {
foo: 'ex1'
}
}
}
render() {
console.log(this.state.FirstTime); //Sorry a typo found in this line
return (
<div>Hey</div>
);
}
componentDidMount() {
let obj = {
bar: 'ex2'
}
let finalData = { ...this.state.FirstTime, ...obj }
this.setState({ FirstTime: finalData })
}
}
const rootElement = document.getElementById("root")
ReactDOM.render(
<App />,
rootElement
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>