I have a code block for submitting a log entry on a particular date.
import React from "react";
import { StyleSheet, View, TextInput, Pressable } from "react-native";
import { Ionicons } from "@expo/vector-icons";
import DateTimePicker from "@react-native-community/datetimepicker";
import { Keyboard } from "react-native";
export default class PostForm extends React.Component {
state = {
body: "",
date: new Date(),
};
setBody = (newBody) => {
this.setState({ body: newBody });
};
setDate = (event, newDate) => {
this.setState({ date: newDate });
};
postEntry = () => {
if (this.state.body.length == 0) {
return;
}
this.props.onSubmit({
body: this.state.body,
date: this.state.date.toISOString(),
});
this.setState({
body: "",
date: new Date(),
});
Keyboard.dismiss();
};
render() {
return (
<View style={styles.vertContainer}>
<View style={styles.horContainer}>
<DateTimePicker
style={styles.dateTime}
value={this.state.date}
accentColor="#E2AFDE"
onChange={this.setDate}
/>
<Pressable style={styles.post} onPress={() => this.postEntry()}>
<Ionicons
style={styles.postIcon}
name={"arrow-forward-outline"}
size={30}
/>
</Pressable>
</View>
<TextInput
style={styles.input}
placeholder="What happened?"
multiline={true}
value={this.state.body}
onChangeText={(newText) => this.setBody(newText)}
maxLength={378}
/>
</View>
);
}
}
const styles = StyleSheet.create({
vertContainer: {
flex: 1,
flexDirection: "column",
},
horContainer: {
flexDirection: "row",
verticalAlign: "center",
justifyContent: "center",
paddingTop: 10,
paddingRight: 10,
justifyContent: "space-between",
},
input: {
width: "100%",
flexWrap: "wrap",
padding: 15,
fontSize: 20,
paddingTop: 10,
},
post: {
backgroundColor: "#E2AFDE",
borderRadius: 10,
alignItems: "center",
justifyContent: "center",
width: 50,
},
postIcon: {
color: "white",
},
dateTime: {},
});
For some reason, when the pressable is pressed, it doesn’t cause the state to be updated to reflect the empty body and new Date. I am currently using setState in postEntry, but when I have console logged after the fact, the state doesn’t properly get updated (and in turn isn’t reflected in the actual view)
import React from "react";
import { StyleSheet, View } from "react-native";
import PostForm from "../components/PostForm";
import { connect } from "react-redux";
import { addEntry } from "../redux/actions";
class PostScreen extends React.Component {
handleSubmit = (form) => {
this.props.addEntry(form);
this.props.navigation.navigate("HomeScreen");
};
render() {
return (
<View style={styles.container}>
<PostForm onSubmit={this.handleSubmit}></PostForm>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "row",
},
});
export default connect(null, { addEntry: addEntry })(PostScreen);
Weirdly I’ve noticed it takes to clicks for it to automatically clear.
2
Answers
All fixed - I ended up moving a lot of the logic into the PostScreen.
PostForm:
PostScreen:
You can use:
I think it is work fine.