I want to use a state in definition of an other state but i get nothing value.
Does anyone have any ideas??
constructor(props) {
super(props);
this.state = {
check : false,
datatotal : this.props.services.map((d) =>
<CheckBox
center
title={d}
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checked= {true}
onPress={() => this.checkBoxClick()}
/>
)
};
}
You can use this inside your Component
constructor(props){
super(props);
this.state = {
check: false
}
}
render() {
<View>
{this.props.services && this.props.services.map(
<CheckBox
center
title={d}
checkedIcon='dot-circle-o'
uncheckedIcon='circle-o'
checked= {true}
onPress={() => this.checkBoxClick()}
/>
)</View>}
}
Hey checkout this link it might help you : https://www.tutorialspoint.com/react_native/react_native_state.htm
Related
Getting started with React. I have two drop-downs in the child component WeatherOptionsView. I'm trying to set it's default value based on the prop array of previously selected values passed from Parent component WeatherContainerView. I also want to set it to the state as the value will change onChange of dropdown going forward.
The UI blows up when I do this. When I print the values of props, I see that the selectedCodes is null. Where am I going wrong with this? Any help will be appreciated. Thanks!
console.log(this.props.isFailed); //false
console.log(this.props.selectedValues); //null
WeatherOptionsContainer.js
class WeatherOptionsContainer extends React.Component {
constructor(props) {
super(props);
this.state = { isFailed: true, isLoading: false, selectedValues: ['City1', 'City2']};
}
render() {
return (
<WeatherOptionsView
isFailed={this.state.isFailed}
isLoading={this.state.isLoading}
selectedValues={this.state.selectedValues}
/>
);
}
}
WeatherOptionsView.js
class WeatherOptionsView extends React.Component {
constructor(props) {
super(props);
this.state = { reasonState: false, selectedValues: this.props.selectedValues };
}
render() {
const cx = classNames.bind(styles);
return (
<ContentContainer fill>
<Spacer marginTop="none" marginBottom="large+1" marginLeft="none" marginRight="none" paddingTop="large+2" paddingBottom="none" paddingLeft="large+2" paddingRight="large+2">
<Fieldset legend="City">
<Grid>
<Grid.Row>
<Grid.Column tiny={3}>
<SelectField selectId="State1" required placeholder="Select" label={["City:"]} error={["Error message"]} isInvalid={this.state.reasonState} defaultValue={this.props.selectedValues[0]}>
<Select.Option value="City1" display="City1" />
<Select.Option value="City2" display="City2" />
</SelectField>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column tiny={3}>
<SelectField selectId="State2" required placeholder="Select" label={["City:"]} error={["Error message"]} isInvalid={this.state.reasonState} defaultValue={this.props.selectedValues[1]}>
<Select.Option value="City1" display="City1" />
<Select.Option value="City2" display="City2" />
</SelectField>
</Grid.Column>
</Grid.Row>
</Grid>
)}
/>
</ContentContainer>
);
}
}
The issue is, you are passing the prop selectedCodes and in the inner component you are using this.props.selectedValues. This should work.
constructor(props) {
super(props);
this.state = { reasonState: false, selectedValues: this.props.selectedCodes };
}
I am trying to send state value from parent to child component.Initially the state value is empty.After an API call,state value get updated but my props is taking the initial empty value.
class Metrics extends React.Component {
constructor(props) {
super(props);
this.state.result:[];
}
submit = e => {
e.preventDefault();
var URL =
"http://localhost:8080/fetchAnalysisData;
this.setState({ formsubmit: true });
fetch(URL, {
method: "GET"
})
.then(res => res.json())
.then(data => {
console.log("Response Success!!");
this.setState({ result: data });
});
};
render(){
return(
<Button onClick={this.submit}
fontSize: "small",
marginLeft: "30%"
}}
>
VIEW RESULT
</Button>
<div className={this.state.formsubmit ? "showDisplay" : "hide"}>
<DipslayBarChart result={this.state.result}></DipslayBarChart>
</div>
)
}
Child Component:
class DipslayBarChart extends React.Component {
constructor(props){
super(props);
}
render(){
return(
<div>
<BarChart width={500} height={300} data={this.props.result}>
<XAxis dataKey="Date" />
<YAxis />
<Tooltip cursor={false} />
<Legend />
<Bar dataKey="Success" stackId="a" fill="#068f12" label />
<Bar
dataKey="Failure"
stackId="a"
fill="#ec0b0b"
/>
</BarChart>
</div>
)
}
}
How to update the prop value once the state is updated?
Write your constructor like this,
constructor(props) {
super(props);
this.state={
result:[]
}
}
Moreover If you are not using the props in the constructor no need to declare constructor. you can declare state like this
state={
result:[]
}
I have a TextInput below :
Normally I am able to read TextInput when there is a change , the problem is the TextInput for password is populated with a default password .
So the user may not need to edit(change) it - therefore not triggering onChangeText method .
import React,{Component} from 'react'
import {View, Text, TextInput } from 'react-native'
export default class App extends Component {
constructor(props){
super(props);
this.state = {
username: '',
password: 12345
}
}
onChangeText = (key, val) => {
this.setState({ [key]: val})
}
render() {
return (
<View style={styles.container}>
<Text>Login Form</Text>
<TextInput
placeholder='Username'
onChangeText={val => this.onChangeText('username', val)}
style={styles.input}
value={this.state.username}
/>
<TextInput
placeholder='Password'
onChangeText={val => this.onChangeText('password', val)}
style={styles.input}
value={this.state.password}
secureTextEntry={true}
/>
</View>
);
}
}
Now , my question is how do I read TextInputs which are not being changed ?
change TextInput value prop to defaultValue. i think that might work. TextInput value prop does't allow to modify existing value.
<TextInput
placeholder='Password'
onChangeText={val => this.onChangeText('password', val)}
style={styles.input}
defaultValue={this.state.password}
secureTextEntry={true}
/>
There is a way to get TextInput value directly from the component via refs.
If the input receives text from value prop you can use _lastNativeText method as in the example below.
export default class App extends Component {
state = {
text: 'Hello!'
}
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
componentDidMount() {
this.printTextInputValue();
}
printTextInputValue = () => {
const input = this.inputRef.current;
console.log(input._lastNativeText);
}
render() {
return (
<View style={styles.container}>
<TextInput value={this.state.text} ref={this.inputRef} />
<Button onPress={this.printTextInputValue} title="Get input value" />
</View>
);
}
}
If the TextInput uses defaultValue prop use _getText method to read the initial value.
export default class App extends Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
componentDidMount() {
this.printDefaultInputValue();
}
printDefaultInputValue = () => {
const input = this.inputRef.current;
console.log(input._getText());
}
printTextInputValue = () => {
const input = this.inputRef.current;
console.log(input._lastNativeText);
}
render() {
return (
<View style={styles.container}>
<TextInput defaultValue="Hello Default!" ref={this.inputRef} />
<Button onPress={this.printTextInputValue} title="Get input value" />
</View>
);
}
}
Do note however that these methods are not officially documented and may be removed in future versions of React Native, so use them at your own discretion.
I'm new to react native and trying event handling and came up with a problem.
Suppose I have a code like this
class Demo extends React.Component {
constructor(props) {
this.textValues = {a: null, b: null};
}
handleChange(event) {
this.textValues['a'] = this.props.customProps;
this.textValues['b'] = event.nativeEvent.text;
}
render() {
return (
<View>
<TextInput
customProps = 'T1'
onChange = {this.handleChange.bind(this)}
/>
<TextInput
customProps = 'T2'
onChange = {this.handleChange.bind(this)}
/>
</View>
)
}
}
I want to access textValues from parent component i.e., Demo as well as customProps from TextInput but
If I bind this with handleChange then this refrence to Demo class and this.props.customProps gives undefined
If I do not bind this with handleChange then this.textValues is not defined and this.props.customProps gives perfect value
But I want to acess both textValues of Demo and customProps of TextInput in handleChange function.
class Demo extends React.Component {
constructor(props) {
super(props);
this.textValues = { a: null, b: null };
}
handleChange = field => (event) => {
console.log(field)
this.textValues[field] = event.nativeEvent.text
}
render() {
return (
<View>
<TextInput onChange={this.handleChange('a')} />
<TextInput onChange={this.handleChange('b')} />
</View>
)
}
}
ReactDOM.render(
<Demo />,
document.getElementById('container')
);
do you want the handleChange function to know which TextInput is called from?
try these codes
<TextInput
customProps = 'T1'
onChange = {(input)=>{
this.handleChange("T1", input)
}}
/>
<TextInput
customProps = 'T2'
onChange = = {(input)=>{
this.handleChange("T2", input)
}}
/>
and the hanleChange function is
handleChange(inputTag, inputText) {...}
I click a button on the navigator, the current screen's one TextInput's is focus.
I need to set the TextInput's instance blur to trigger the textChange function to do something.
In my case, the cursor of TextInput is blinking all the time.
refs.username.blur() does not work.
My code :
class UploadRecordII extends Component{
static navigationOptions = ({ navigation, screenProps }) => ({
headerRight: (<Button containerStyle={{marginRight: 12,}} onPress={ UploadRecordII.onSubmit}>
<Text style={{color: 'white',fontSize: 18,}}>next</Text>
</Button>),
});
.....
static onSubmit() {
let that = UploadRecordII.instance;
debugger;
that.refs.username.blur();
debugger;
that.props.commitCreateRecordUpdate(that.refs.username._lastNativeText,that.imageList)
that.props.navigation.navigate('Record3');
}
...... in render(){
....
<TextInput ref = 'username' placeholder='' editable = {true} maxLength = {500}
keyboardType='default' multiline={true}
style={styles.input} underlineColorAndroid='rgba(0,0,0,0)'
onBlur={ ()=> this.textChange()}
clearButtonMode='always' placeholderTextColor='#D6D0D8'></TextInput>
...
}
refs don't work as strings anymore as expected. You need to define your ref e.g.
class UploadRecordII extends Component {
constructor(props) {
super(props);
this.usernameInput = null;
}
onSubmit() {
this.usernameInput.blur();
}
render() {
return (
<TextInput ref={(input) => this.usernameInput = input} ... />
)
}
}