React Component does not render after the state changes - javascript

Hello I have a problem with re rendering the component below you can see my code for the first screen within that I have a custom component:
class Ahelle extends React.Component{
constructor(props){
super(props)
this.state={
mamad:10
}
}
render(){
return (
<View style={{backgroundColor:"white"}}>
<ScrollView>
<CustomSlider defaultValue={0} />
<CustomSlider defaultValue={this.state.mamad} disabled={true}/>
<TouchableOpacity style={{width:100,height:100,alignSelf:"center"}} onPress={()=>{this.setState({mamad:20})}}><Text>dddd</Text></TouchableOpacity>
</ScrollView>
</View>
);
}
}
Here I have a custom component and I pass a default value for showing but when I change the state , it is not changing the value I passed as props.
here is my custom slider component and its state, props and any other details.
class Test extends React.Component{
constructor(props){
console.log(props)
super(props)
this.state = {
value: props.defaultValue
};
}
render(){
return(
<Slider
style={{width: wp("70%")}}
value={this.state.value}
/>
)
}
}
export default Test;
SEE THE PROBLEM IN ACTION
Thank you for your time

Your slider component never does anything with updated prop values that are passed. Coincidentally, it's also a react anti-pattern to store passed props in local component state. You can, and should, consume them directly. Just pass this.state.mamad to the value prop and consume. You can also pass along any additional props by spreading them in to the slider component.
class Test extends React.Component {
render() {
return (
<Slider
style={{ width: wp("70%") }}
value={this.props.value}
{...this.props}
/>
);
}
}
export default Test;
Usage
<CustomSlider value={this.state.mamad} disabled={true} />
If you really wanted to store the passed defaultValue prop and keep it updated, then implement the componentDidUpdate lifecycle function. Note, this is not the recommended solution.
class Test extends React.Component {
constructor(props) {
console.log(props);
super(props);
this.state = {
value: props.defaultValue
};
}
componentDidUpdate(prevProps) {
const { defaultValue } = this.props;
if (prevProps.defaultValue !== defaultValue) {
this.setState({ value: defaultValue});
}
}
render() {
return <Slider style={{ width: wp("70%") }} value={this.state.value} />;
}
}
export default Test;

Your code is correct. I tested it.
App.js
import React from "react";
import { Text, View, ScrollView, TouchableOpacity } from "react-native";
import CustomSlider from "./CustomSlider";
export default class Ahelle extends React.Component {
constructor(props) {
super(props);
this.state = {
mamad: 10,
};
}
render() {
return (
<View style={{ backgroundColor: "white" }}>
<ScrollView>
<CustomSlider defaultValue={0} />
<CustomSlider defaultValue={this.state.mamad} disabled={true} />
<TouchableOpacity
style={{ width: 100, height: 100, alignSelf: "center" }}
onPress={() => {
this.setState({ mamad: 20 });
}}
>
<Text>dddd</Text>
</TouchableOpacity>
</ScrollView>
</View>
);
}
}
CustomSlider.js
import React from "react";
import { Text } from "react-native";
export default class CustomSlider extends React.Component {
render() {
return <Text>defaultValue: {this.props.defaultValue}</Text>;
}
}
Result:
View Result

Related

React native View' cannot be used as a JSX component. Its instance type 'View' is not a valid JSX element

I´am currently getting the following error on the View component inside App.tsx: 'View' cannot be used as a JSX component. Its instance type 'View' is not a valid JSX element
I think the issue is related to the library
import React from 'react';
import {View,Text,StyleSheet, Button} from 'react-native'
import {createSwitchNavigator} from 'react-navigation'
const styles = StyleSheet.create({
txt:{
fontSize: 48
},
view: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}
})
class screenComponent1 extends React.Component {
render() {
return(
<View>
<Button onPress={() => this.props.navigation.navigate('screenroute2')} title='next page'/>
</View>
)
}
}
class screenComponent2 extends React.Component {
render() {
return(
<View>
<Button onPress={() => this.props.navigation.navigate('screenroute1')} title='next page'/>
</View>
)
}
}
const AppNavigator = createSwitchNavigator({
screenroute1: screenComponent1,
screenroute2: screenComponent2,
})
export default class App extends React.Component {
render() {
return <AppNavigator/>
}
}

Call function with setState from other component

I have the following setup:
import {getNewImage} from '...'
export default class FirstClass extends Component {
constructor() {
super();
this.state = {
imageURL: 'www.test.com/new.jpg',
}
}
update = () => {
this.setState({
imageURL: 'www.test.com/updated.jpg',
})
}
render() {
return (
<View>
<Image
source={{ uri: this.state.imageURL }}
/>
</View>
);
}
}
import Class1 from '...'
export default class SecondClass extends Component {
render() {
return (
<TouchableOpacity onPress={() => new FirstClass().update()}>
<Class1></Class1>
</TouchableOpacity>
);
}
}
The problem is: it doesn't update the imageURL. I tried multiple things. Logging this inside of update gave back the right object. But trying to log the this.setState() gives an undefinded back.
I suppose by Class1 you mean FirstClass.
you should use the reference of the component using ref, not creating new instance of FirstClass class
checkout this code
export default class SecondClass extends Component {
private firstClass = null;
render() {
return (
<TouchableOpacity onPress={() => this.firstClass.update()}>
<Class1 ref={ref => this.firstClass = ref} />
</TouchableOpacity>
);
}
}
You can try to update state in Class1 similar to what do you want by the react reference.
But on my opinion this is non a good case and predictable behavior to change child component state from parent.
As another options you can add additional state to the SecondClass and pass it via props to child component. And inside Class1 in getDerivedStateFromProps based on that prop change state.
export default class FirstClass extends Component {
constructor() {
super();
this.state = {
isNeedToUdpate: false,
imageURL: "www.test.com/new.jpg"
};
}
static getDerivedStateFromProps(props, state) {
if (props.isNeedToUdpate !== state.isNeedToUdpate) {
return {
isNeedToUdpate: props.isNeedToUdpate,
imageURL: "www.test.com/updated.jpg"
};
}
return null;
}
render() {
return (
<View>
<Image source={{ uri: this.state.imageURL }} />
</View>
);
}
}
export default class SecondClass extends Component {
constructor() {
super();
this.state = {
isNeedToUpdateClass1: false
};
}
render() {
return (
<TouchableOpacity
onPress={() => {
this.setState({ isNeedToUpdateClass1: true });
}}
>
<Class1 isNeedToUpdate={this.state.isNeedToUpdateClass1}></Class1>
</TouchableOpacity>
);
}
}

React native: passing image path as params through 2 components

i'm trying to pass an image path down to one component via react-navigation params and from that component to a third one as a prop.
This is a chat application and the structure of the components is:
ChatsMain.js --> (click on SingleChat, passing parameters when navigating) --> SingleConversation.js --> Message
I can pass 'name' as a parameter, but not the uri of an image, not even by assigning it to variables.
The name that i see on the SingleChat is passed without problems to the correspondent conversation, but when i pass the image i get the error:
'Failed prop type: Invalid prop source supplied to Image.'
I hope it's clear enough, i don't think it's the correct way to do this, but i am new to react native!
ChatsMain.js
const imageNames = {
juf: require('../assets/juf.png'),
meester: require('../assets/meester.png'),
groep: require('../assets/groep.png'),
onderwerpen: require('../assets/onderwerpen.png')
}
export default class ChatsMain extends React.Component {
render() {
return (
<SingleChat
image={imageNames.juf}
backgroundColor={yellow}
borderColor={blue}
name='Juf Elsa'
onPress={() => this.props.navigation.navigate('SingleConversation', {name: 'Juf Elsa', image: imageNames.juf})}
/>
)
SingleConversation.js
export default class SingleConversation extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
title: navigation.getParam('name', 'Chat'),
headerStyle: [titleBar, { backgroundColor: yellow }],
headerTitleStyle: [title, { color: blue }]
}
}
render() {
return (
<View style={chatMainContainer}>
<ScrollView style={chatsContent}>
<Message image={({navigation}) => navigation.getParam('image', 'image')} />
</ScrollView>
</View>
);
}
}
Message.js
export default class ReceivedFirst extends React.Component {
render(
){
return(
<View style={textWithPicture}>
<View style={[chatPhotoContainer, { borderColor: yellow }]}>
<Image source={this.props.image} style={{ width: 70, height: 70}} />
.....
.....
)
You can use this.props.navigation.state.params instead this.props.navigation.getParam
export default class SingleConversation extends React.Component {
constructor(props) {
super(props);
this.state = {
image: this.props.navigation.state.params.image
};
}
...
Message image={this.state.image} />
OR
You need to get a Navigation from the props.
render() {
const { navigation } = this.props
return (
<View style={chatMainContainer}>
<ScrollView style={chatsContent}>
<Message image={() => navigation.getParam('image', 'image')} />
</ScrollView>
</View>
);
}

"undefined is not an object" when trying to access TextInput of the sibling component using references

in Parent component, I'm trying to focus the TextInput of second Child component when submit button is pressed in the TextInput of the first Child component but this error comes up: error message
Child.js
import React from "react";
import { View, TextInput} from "react-native";
export default class Child extends React.Component {
focus = ref => {
ref.input.focus();
};
render() {
return (
<View>
<TextInput
placeholder='enter text'
onSubmitEditing={() => {
this.focus(this.props.destinationRef);
}}
ref={input => {
this.input = input;
}}
/>
</View>
);
}
}
Parent.js
import React from "react";
import Child from "./Child";
import { View, StyleSheet } from "react-native";
export default class Parent extends React.Component {
// componentDidMount() {
// setTimeout(() => {
// this.two.input.focus();
// }, 3000);
// }
render() {
return (
<View style={styles.container}>
<Child
destinationRef={() => {
if (!this.two) return this.two;
}}
ref={input => {
this.one = input;
}}
/>
<Child ref={input => (this.two = input)} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center"
}
});
Note that when I uncomment the componendDidMount, second TextInput successfully focuses three seconds after mounting.
I think the problem in render update. In first render time destinationRef is undefined, parent state not updated or force updated so props not updated too.
I try little bit optimize your code. You can use arrow function to bind this:
import React from "react";
import Child from "./Child";
import { View, StyleSheet } from "react-native";
export default class Parent extends React.Component {
_makeFocus(){
this.two.input.focus();
}
handleOnSubmit(){
this._makeFocus();
}
render() {
return (
<View style={styles.container}>
<Child
onSubmit={this.handleOnSubmit.bind(this)}
ref={input => {
this.one = input;
}}
/>
<Child ref={input => (this.two = input)} />
</View>
);
}
}
I would change the logic a little bit since I think the ref is giving you problems.
Parent:
<View style={styles.container}>
<Child next={this.two} ref={comp => this.one = comp}/>
<Child next={this.one} ref={comp => this.two = comp}/>
</View>
Child:
<TextInput
placeholder='enter text'
onSubmitEditing={() => {
if (this.props.next)
this.props.next.focus();
}}
/>
EDIT:
Your approach was correct I believe, I would just update the parent into this:
export default class Parent extends React.Component {
constructor(props){
super(props);
this.references = {};
}
onFocus = (ref) => {
this.references[ref].focus();
}
render() {
return (
<View style={styles.container}>
<Child
destinationRef={'two'}
onFocus={this.onFocus}
ref={input => this.references['one'] = input}
/>
<Child ref={input => this.references['two'] = input} />
</View>
);
}
}
and your child to:
export default class Child extends React.Component {
render() {
return (
<View>
<TextInput
placeholder='enter text'
onSubmitEditing={() => {
this.props.onFocus(this.props.destinationRef);
}}
/>
</View>
);
}
}

how get values of components react native

I want to get the value of the email and passowrd in my Form.js, so that click click button can pass them a client api
1. this is my class src/components/login/Form.js
import React, { Component } from 'react';
import {
KeyboardAvoidingView,
StyleSheet,
TouchableHighlight,
Image,
} from 'react-native';
import UserInput from "./UserInput";
import usernameImg from '../../images/Iconperson.png';
import passwordImg from '../../images/Iconlock.png';
import eyeImg from '../../images/eye.png';
export default class Form extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
};
}
_onPress() {
console.warn("email", this.state.email)
console.warn("password", this.state.password)
}
render() {
return (
<KeyboardAvoidingView behavior='padding'
style={styles.container}>
<UserInput source={usernameImg}
onChangeText = {(email) => this.setState({email})}
keyboardType = 'email-address'
placeholder='Username'
autoCapitalize={'none'}
returnKeyType={'done'}
autoCorrect={false} />
<UserInput source={passwordImg}
onChangeText = {(password) => this.setState({password})}
placeholder='Password'
returnKeyType={'done'}
autoCapitalize={'none'}
autoCorrect={false} />
<TouchableHighlight
onPress={this._onPress}
activeOpacity={1} >
<Text>LOGIN</Text>
</TouchableHighlight>
</KeyboardAvoidingView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
}
});
2. this is my class src/components/login/UserInput.js
import React, { Component , PropTypes} from 'react';
import Dimensions from 'Dimensions';
import {
StyleSheet,
View,
TextInput,
Image,
} from 'react-native';
const DEVICE_WIDTH = Dimensions.get('window').width;
const DEVICE_HEIGHT = Dimensions.get('window').height;
export default class UserInput extends Component {
render() {
return (
<View style={styles.inputWrapper}>
<Image source={this.props.source}
style={styles.inlineImg} />
<TextInput style={styles.input}
onChangeText = {(this.props.ChangeText) =>
this.setState({field})}
placeholder={this.props.placeholder}
secureTextEntry={this.props.secureTextEntry}
autoCorrect={this.props.autoCorrect}
autoCapitalize={this.props.autoCapitalize}
returnKeyType={this.props.returnKeyType}
placeholderTextColor='white'
keyboardType ={this.props.keyboardType}
underlineColorAndroid='transparent' />
</View>
);
}
}
UserInput.propTypes = {
ChangeText : PropTypes.string,
source: PropTypes.number.isRequired,
placeholder: PropTypes.string.isRequired,
keyboardType : PropTypes.string,
secureTextEntry: PropTypes.bool,
autoCorrect: PropTypes.bool,
autoCapitalize: PropTypes.string,
returnKeyType: PropTypes.string,
};
const styles = StyleSheet.create({
input: {
backgroundColor: 'rgba(255, 255, 255, 0.2)',
width: DEVICE_WIDTH - 40,
height: 40,
marginHorizontal: 20,
paddingLeft: 45,
borderRadius: 20,
color: '#ffffff',
},
inputWrapper: {
flex: 1,
},
inlineImg: {
position: 'absolute',
zIndex: 99,
width: 22,
height: 22,
left: 35,
top: 9,
},
});
As you are typing into the TextInput I see you are trying to change the state in the Form component. For this to happen correctly, setState needs to be called from the Form component. There are a couple functions currently being passed down through props:
(email) => this.setState({email})
// and
(password) => this.setState({password})
Looking at how those are being used in your UserInput component, whenever a new character is added to that text box, invoke the function above. so when this.setState() is called, it is saying UserInput.setState(). Since we want to change the state in Form we have to bind those functions to the parent component.
Instead of passing the functions directly to props, let's add some user methods:
export default class Form extends Component {
constructor(props) {}
_onChangeEmail(email) {
this.setState(Object.assign({}, state, { email })); // good practice for immutability
}
_onChangePassword(password) {
this.setState(Object.assign({}, state, { password })); // good practice for immutability
}
render() {}
}
Next, we need to bind these class methods to itself. That way no matter where these are called, this will always point to the Form component. This is most commonly done in the constructor:
export default class Form extends Component {
constructor(props) {
super(props)
this.state = {}
// this is where we do the binding
this._onChangeEmail = this._onChangeEmail.bind(this)
this._onChangePassword = this._onChangePassword.bind(this)
}
_onChangeEmail(email) { /* code */}
_onChangePassword(password) { /* code */}
render() {}
}
Now pass these down to the UserInput component through props:
// Form.js
render() {
return (
<KeyboardAvoidingView>
<UserInput onChangeText={this._onChangeEmail} />
<UserInput onChangeText={this._onChangePassword} />
</KeyboardAvoidingView>
)
}
These methods should now be used when the user inputs text:
export default class UserInput extends Component {
render() {
return (
<View>
<Image />
<TextInput onChangeText = {this.props.onChangeText} />
</View>
);
}
}
Bonus: You also should add a property 'value' to the text input:
export default class UserInput extends Component {
render() {
return (
<View>
<Image />
<TextInput
onChangeText={this.props.onChangeText} />
value={this.props.textValue}
</View>
);
}
}
And make sure it is passed down from the parent component:
// Form.js
render() {
return (
<KeyboardAvoidingView>
<UserInput
onChangeText={this._onChangeEmail}
textValue={this.state.email}/>
<UserInput
onChangeText={this._onChangePassword}
textValue={this.state.password}/>
</KeyboardAvoidingView>
)
}
The value of TextInput may be retrieved through its _lastNativeTextproperty.
this.refs.myTextInput._lastNativeText
See this answer

Categories