I want to get checked friends using checkbox. But I not quite sure how i will achieve it, hope someone can help me.
This is my state:
state = {checked: false}
This is where I want to map array
{this.props.navigation.getParam('friends').map((name, key) => (
<View>
<Text>{name}</Text>
<CheckBox
checked={this.state.checked}
onPress={(val)=>{}}
/>
</View>))}
Note: Or Could someone write me an app/code snippet in snack.expo.io how to get only checked checkbox value
You can write a custom checkbox component
export default class CustomCheckbox extends Component {
constructor(props) {
super(props);
this.state = {
checked: false,
};
}
toggleChange(){
this.setState({checked: !this.state.checked});
}
render() {
return (
<View>
<Text>{this.props.name}</Text>
<CheckBox
checked={this.state.checked}
onPress={() => this.bind.toggleChange(this)}
/>
</View>
);
}
}
and import your CustomCheckbox component
import CustomCheckbox from "your CustomCheckbox.js path"
{this.props.navigation.getParam('friends').map((name, key) => (
<View>
<CustomCheckbox name={name} />
</View>
))}
Your code is pretty good to go, you just need to update a bit. You have following two options:
Your friend's array should have checked key within each containing object, then you can simply do something like this.
{
this.props.navigation.getParam('friends').map((item, key) => (
let {name, checked} = item // item is an object from friends array,the and it have name, checked and other keys
<View>
<Text>{name}</Text>
<CheckBox
checked={checked}
onPress={(val)=>{}}
/>
</View>))
}
Other is you to save the name of the person as key and true/false as the checked state, eg :
toggleCurrentFirendState = (item)=>{
this.setState((prevState)=>{
let {name} = item //get name from clicked friend from the list
return {
...prevState, //used spread operator, so that other states doesn't get mutat.
[name]:!prevState[name] //toogle state of clicked item
}
})
}
//within your render
{
this.props.navigation.getParam('friends').map((item, key) => (
let {name} = item // item is an object from friends array,the and it have name, checked and other keys
<View>
<Text>{name}</Text>
<CheckBox
checked={name ===this.state[name]} //see change
onPress={(val)=>{this.toggleCurrentFirendState(item)}}
/>
</View>))
}
Related
I'm using react-native-phone-number-input and i want to delete the call code from the number if the user types it.
my solution is :
class PhoneUserInput extends PureComponent {
...
<PhoneInput
ref={this.myRef}
onChangeFormattedText={(value) => {
if (value.substr(`+${this.myRef.current?.getCallingCode()}`.length)
.startsWith(`+${this.myRef.current?.getCallingCode()}`)) {
value = value.substr(`+${this.myRef.current?.getCallingCode()}`.length)
.replace(`+${this.myRef.current?.getCallingCode()}`, ''));
}
onChangeFormattedText(value);
console.log('formated value'+value);
}
}}
/>
}
I tried to the same thing on onChangeText props but it's doesn't give the effect instantly on the component.
Please try to do your work with
onChangeText={ (_text)=>{ //Your code} }
AND add :
value={value}
Here is a working example :
<PhoneInput
ref={phoneInput}
defaultValue={value}
value={value}
defaultCode="FR"
layout="first"
placeholder={label}
containerStyle={styles.phoneContainer}
onChangeText={(text) => {
setValue(text)
}}
onChangeFormattedText={(text) => {
setFormattedValue(text)
}}
withDarkTheme
withShadow
/>
I am creating react-native mobile app. I have an array with some values. I want to set array's value into input field. I have added value in the fields but i can't able to update these values. I have set my values in a qty variable like this:
constructor(props) {
super(props);
this.state = {
qty:[],
}
}
componentWillMount() {
var ids = [];
this.props.data.map((dataImage,Index) => {
dataImage['pro-name'] != undefined && (
ids.push({'qty':dataImage['pro-qty']})
)
})
this.setState({qty:ids})
}
render() {
return {
this.props.data.map((dataImage,Index)=>(
<View key={Index} style={productStyle.cartview}>
{dataImage['pro-name'] && (
<View style={productStyle.cartmain}>
<Input value={this.state.qty[Index]['qty']} onChange={this.handleChangeInput.bind(this)} style={{width:40,height:40,textAlign:'left'}} />
</View>
)}
</View>
))
}
}
Its showing values properly into the input field but i can't able to type anything into the field to update the values. what can i do for this
I will suggest you to move your input container into separate class, its better approach and each component will handle its own state. Its easy to handle and will result better in performance too.
components = []
render() {
return this.props.data.map((item, index) => (
<CustomComponent data={item} index={index} ref={(ref) => this.components[index] = ref} />
))
}
You can then get child (CustomComponent) value from its ref.
this.components[index].getValue()
this.components[index].setValue('Value');
You will need to create these functions (getValue & setValue) in CustomComponent class.
solution
Here is solution to your query. You need to install lodash or find other solution to make a new copy qty.
<Input onChangeText={(text) => this.handleChangeText(text, index)} />
handleChangeText = (text, index) => {
const qty = _.cloneDeep(this.state.qty);
qty[index] = {
qty: text
}
this.setState({qty})
}
Your Input's value is set to this.state.qty[Index]['qty']. And to change it on text edit, you can do it like this. You do not need to bind the function, instead use an arrow function like this.
onChangeText={ (newValue) => {
this.setState({ <your-input-value-state>:newValue })
}}
You have to update the value of each Input individually on onChange event.
Replace your with Input with this
<Input value={this.state.qty[Index]['qty']}
onChange={this.handleChangeInput.bind(this, Index)}
style={{width:40,height:40,textAlign:'left'}}
/>
and update the state accordingly with the Index when the event is called
handleChangeInput(index, value){
let {qty} = this.state;
let qty_update = qty.slice();
qty_update[index]['qty'] = value;
this.setState({qty: qty_update});
}
I have a child Picker and it should pass selected value to it's parent. Components are in different .js files if it's important.
How can I pass the states of selected items?
parent
<RegionPicker regions={this.props.navigation.state.params.regionsJSON}/>
child:
export default class RegionPicker extends Component {
constructor(props) {
super(props);
this.state = {
selected1: '1',
selected2: '1'
};
}
onValueChange1(value: string) {
this.setState({selected1: value},
()=>{ console.log('new',this.state.selected1)}
);
}
onValueChange2(value: string) {
this.setState({selected2: value},
()=>{ console.log('new',this.state.selected2)}
);
}
render() {
return (
<View>
<Form>
<Item inlineLabel>
<Label style={{fontSize:16}}>Region</Label>
<Picker
iosHeader="Select one"
mode="dropdown"
placeholder='...'
selectedValue={this.state.selected1}
onValueChange={this.onValueChange1.bind(this)}
>
{this.getRegions(this.props.regions).map((item, index) => {
return (<Picker.Item label={item} value={item} key={index}/>)
})}
</Picker>
</Item>
<Item inlineLabel last>
<Label style={{fontSize:16}}>Suburb</Label>
<Picker
iosHeader="Select one"
mode="dropdown"
placeholder='...'
selectedValue={this.state.selected2}
onValueChange={this.onValueChange2.bind(this)}
>
{this.getSuburbs(this.state.selected1).map((item, index) => {
return (<Picker.Item label={item} value={item} key={index}/>)
})}
</Picker>
</Item>
</Form>
</View>
);
}
}
I would appreciate for any help and ideas.
In your parent, create a function that will capture your RegionPicker value. In this example, myFunction.
myFunction = (value) => {
console.log(value);
}
Then pass down your function as a prop, like so:
<RegionPicker
regions={this.props.navigation.state.params.regionsJSON}
onChange={e => { this.myFunction(e) }}
/>
Inside of RegionPicker you can simply call your function within onValueChange1() and onValueChange2().
this.props.onChange(value);
You should also .bind() your functions within the constructor. So inside of your RegionPicker you can add
this.onValueChange1 = this.onValueChange1.bind(this);
this.onValueChange2 = this.onValueChange2.bind(this);
And then just call
this.onValueChange1 in your Picker's onValueChange function.
As i thing you can do one thing you can get the value in the parent component
onValueChange={()=>{this.props.onValueChange1()}}
And in the component you call this function so you will get value
<RegionPicker onValueChange1={()=>{this.calculate()}}/>
calling the function in parent state will be
calculate (value: string){
**Do you logic stuff here **
}
May you get the value now
How to get the Id of the element in onPress event handler.
I am adding elements dynamically and wants to know in the event handler of onPress of these elements to store in the state which elements are clicked.
Here is the code i have
export default class App extends Component {
constructor(props){
super(props);
this.getElements= this.getElements.bind(this);
this.selectElement = this.selectElement.bind(this);
}
componentWillMount(){
this.state = {
noOfElements :10
}
}
selectElement(e,key){
console.log('selectElement() : key=',key);
}
getElements(){
let elements =[];
for(let index=0;index<this.state.noOfElements;index++){
elements.push(
<View key={'View_'+index} style={{flex:1}}>
<Button
key={'View_'+index}
id={index}
onPress={(e,index) => {this.selectElement(e,index)}}
title={'Button-'+index}
/>
</View>
);
}
return elements;
}
render(){
let elements = this.getElements();
return(
<View style={styles.container}>
<Text>Test</Text>
{elements}
</View>
);
}
}
I tried just passing the key like
onPress={(index) => {this.selectElement(index)}}
with no success..
Not sure what i am doing wrong.
The way you have it, i think index would come up undefined, just remove index as an argument in your onPress so it grabs index from the for loop. Also you can prob refactor it using map.
onPress={(e) => this.selectElement(e,index)}
Changed the event handler as below and it is working fine now.
onPress={this.selectElement.bind(this,index)}
and the function now just accepts the index
selectElement(key){
console.log('selectElement() : Index=',key);
}
I've trying to set up a change event if someone modifies a switch component. The approach is to design a view that contains multiple switches and allows the user to set the state per each notification that will end up in a POST api-call. Futher, I'd like to load the initial values from a api-call.
How can I access the state (weather it's checked / unchecked) in my onChangeFunction? And how can I get an element using their ID or name? (same as in HTML/CSS with #mySwitch.setValue(true)?
Given code:
class Settings extends Component {
onChangeFunction(type, props) {
Alert.alert("changed", "==> " + props.state)
}
render() {
return (
<View style={styles.container}>
<Switch onValueChange={this.onChangeFunction.bind(this, "TASK_CREATED", this.props)} value={this.state} />
</View>
);
}
}
You have a mess there between the propsand the state concept. You can do:
class Settings extends Component {
state = {
taskCreated: false,
};
onChangeFunction(newState) {
this.setState(newState, () => Alert.alert("Changed", "==> " + this.state));
}
render() {
return (
<View style={styles.container}>
<Switch onValueChange={(value) => this.onChangeFunction({taskCreated: value})}
value={this.state.taskCreated}
/>
</View>
);
}
}
Notice that this.setState is asynchronous so you can safely read its value using the callback that the method provides.