Change Textinput value when rendering Using .map() React native - javascript

i am using map function to render my component which have textInput . I want to change value of textInput using onchangeText function.
//main component
const [Value0, setValue0] = useState('');
const [Value1, setValue1] = useState('');
const [Value2, setValue2] = useState('');
..
const handleOnSubmit = () => { //fired when click from this
compnent button
console.log(Value0,"Value0");
console.log(Value1,"Value1");
}
//in my return i use :
{
data.map((item, id) => {
return (
<ViewDeatilCard1 key={id} /> //data having length 4
)
})
}
<ViewDeatilCard1 key={id} setChangeText={(value)=>{`'setValue${id}${(value)}'`}} /> //this
<ViewDeatilCard1 key={id} setChangeText={()=>{`'setValue${id}'`}} /> //this
<ViewDeatilCard1 key={id} setChangeText={`'setValue${id}'`} /> //this
// none of this work
// in my component i use
export const ViewDeatilCard1 = ({
setChangeText
}) => {
console.log(setChangeText,"setChangeText");
return (
<View style={styles.container}>
<View style={styles.body}>
<FormInput
style={styles.bodyText}
labelText="Enter pick up loaction"
iconName="null"
onChangeText={setChangeText}
/>
</View>
</View>
)}
how can i change my value using this approach

Related

React native: Update value of object in array in state

I have a component which changes the state when checkbox is checked and the data needs to be updated of the object in the array.
The component state looks something like this
{
key:1,
todo:"Something",
isChecked:false
}
i have 3 files:
AddTodo.js Which passes state & setState to an component TodoList which passes it the subcomponent TodoItem.
I am unable to update the state from TodoItem , I need to implement a function that finds the object from array and updates its isChecked state.
AddTodo.js
function AddTodo() {
const [state, setState] = useState(false);
const [todos, addTodos] = useState([]);
var keys = (todos || []).length;
return (
<View style={styles.container}>
<Modal
animationType="slide"
transparent={true}
visible={state}
statusBarTranslucent={true}
>
<View style={styles.itemsContainer}>
<GetInfoDialog
state={state}
stateChange={setState}
addItem={addTodos}
numKeys={keys}
/>
</View>
</Modal>
{(todos || []).length > 0 ? (
<TodoList data={todos} updateState={addTodos} />
) : null}
<TouchableOpacity
style={styles.btn}
onPress={() => {
setState(true);
}}
>
<Text style={styles.text}>Add New</Text>
</TouchableOpacity>
</View>
);
}
TodoList.js
function TodoList(props) {
return (
<View style={styles.todoList}>
<FlatList
data={props.data}
renderItem={({ item }) => {
console.log(item);
return (
<TodoItem
list={props.data}
itemKey={item.key}
todo={item.todo}
isChecked={item.isChecked}
updateState={props.updateState}
/>
);
}}
backgroundColor={"#000000"}
alignItems={"center"}
justifyContent={"space-between"}
/>
</View>
);
}
TodoItem.js
function TodoItem(props) {
const [checked, setCheck] = useState(props.isChecked);
return (
<View style={styles.todoItem}>
<Checkbox
value={checked}
onValueChange={() => {
setCheck(!checked);
}}
style={styles.checkbox}
/>
<Text style={styles.text}>{props.todo}</Text>
</View>
);
}
renderItem={({ item, index }) => {
console.log(item);
return (
<TodoItem
list={props.data}
itemKey={item.key}
todo={item.todo}
isChecked={item.isChecked}
updateState={props.updateState}
setChecked={(value)=>{
let updatedList = [...yourTodosList]
updatedlist[index].isChecked=value
setTodos(updatedList)
}}
/>
);
}}
and in your todo item
onValueChange={(value) => {
props.setChecked(value);
}}
i also don't think that you need an is checked state in your todo component since you are passing that through props (so delete const [checked, setCheck] = useState(props.isChecked) line and just use the value you are getting from props.isChecked)
didn't pay much attention to your variable names but this should put you on the right track
as per React Native Hooks you have to call
useEffect(() => {
setCheck(checked);
}, [checked]) // now this listens to changes in contact
in TodoItem.tsx

Get only undefined value from my global variable configured with Context

I have an React Native app with two pages. On the first page I have a picker from which I need the data from in the second page. I try to use Context for making sate globally available but I didn't get it to work till now because I only get undefined types at the position where I wanna insert the global state and not the value who was selected from the picker. I dont't get any errors but the field where the picker value should be represented is empty.
File from which I wanna get state from:
const FirstFile = () => {
const [selectedValueRound, setSelectedValueRound] = useState("10 rounds");
return (
<View>
<RoundContext.Provider
value={[selectedValueRound, setSelectedValueRound]}
>
<View>
<Picker
selectedValue={selectedValueRound}
onValueChange={(itemValue, itemIndex) =>
setSelectedValueRound(itemValue)
}
>
<Picker.Item label="1 round" value="0"></Picker.Item>
<Picker.Item label="2 rounds" value="1"></Picker.Item>
</Picker>
</View>
</RoundContext.Provider>
</View>
);
};
Context file:
export const RoundContext = createContext(false);
Navigation file where I wrap my context around
const Stack = createNativeStackNavigator();
const {selectedValueRound, setSelectedValueRound} = useContext(RoundContext);
const MyStack = () => {
return (
<RoundContext.Provider value={[selectedValueRound, setSelectedValueRound]}>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="FirsFile" component={FirsFile} />
<Stack.Screen name="SecondFile" component={SecondFile} />
</Stack.Navigator>
</NavigationContainer>
</RoundContext.Provider>
);
};
File where I try to insert the global value:
const SecondFile = () => {
const [selectedValueRound, setSelectedValueRound] = useContext(RoundContext);
return (
<View>
<Text>{selectedValueRound}</Text>
</View>
);
};
export default SomeFile;
You also need to define context provider and wrap your app into it.
export const RoundContextProvider = ({children}) => {
const stateTuple = useState(false);
return <RoundContext.Provider value={stateTuple}>{children}</RoundContext.Provider>;
}
<RoundContextProvider>
<YourApp/>
</RoundContextProvider>
then you can use it as you described in the question: const [selectedValueRound, setSelectedValueRound] = useContext(RoundContext);
You must declare the state and the context provider in the top parent component. The children should only consume the values from the context.
The parent component
const MyStack = () => {
const [selectedValueRound, setSelectedValueRound] = useState("10 rounds");
const contextValue = useMemo(
() => [selectedValueRound, setSelectedValueRound],
[selectedValueRound]
);
return (
<RoundContext.Provider value={contextValue}>
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="FirsFile" component={FirsFile} />
<Stack.Screen name="SecondFile" component={SecondFile} />
</Stack.Navigator>
</NavigationContainer>
</RoundContext.Provider>
);
};
Note that I used useMemo to prevent passing a new array to the context when selectedValueRound did not change.
The children
const FirstFile = () => {
const [selectedValueRound, setSelectedValueRound] = useContext(RoundContext);
return (
<View>
<View>
<Picker
selectedValue={selectedValueRound}
onValueChange={itemValue => setSelectedValueRound(itemValue)}
>
<Picker.Item label="1 round" value="0"></Picker.Item>
<Picker.Item label="2 rounds" value="1"></Picker.Item>
</Picker>
</View>
</View>
);
};
const SecondFile = () => {
const [selectedValueRound] = useContext(RoundContext);
return (
<View>
<Text>{selectedValueRound}</Text>
</View>
);
};

SearchBar from react-native-elements with FlatList only allows me to type characters one by one

I'm using SearchBar from react-native-elements in my application inside a functional component.
However there's one issue I'm unable to fix: I can only type characters one by one. I cannot continuously write my text inside my bar and then search. Instead I must type every character ony by one to find a specific word.
Here's my code:
export default function InstitutionsScreen({navigation}) {
const [institutions, setInstitutions] = useState('');
const [refresh, setRefresh] = useState(false);
const [fullData, setFullData] = useState([]);
const [value, setValue] = useState('');
useEffect(() => {
if(!institutions) {
setRefresh(false);
getInstitutions();
}
}, []);
const contains = (institutionName, query) => {
if (institutionName.includes(query)) {
return true
}
return false
}
const handleSearch = text => {
setValue(text);
const formattedQuery = text.toLowerCase()
console.log("flaco me diste " + formattedQuery)
const data = filter(fullData, inst => {
return contains(inst.name.toLowerCase(), formattedQuery)
})
setInstitutions(data);
}
const onRefresh = () => {
setRefresh(true);
getInstitutions();
};
const renderHeader = () => (
<View
>
<SearchBar
lightTheme
clearIcon
onChangeText={(text) => handleSearch(text)}
value={value}
placeholder='Buscar...' />
</View>
)
if (!institutions || refresh) {
return (
<ScrollView contentContainerStyle={{alignItems: "center", flex: 1, justifyContent: 'center'}}>
<Spinner isVisible={true} size={100} type={'Pulse'} color={'#013773'}/>
</ScrollView>
);
} else {
return (
<View>
<SafeAreaView>
<FlatList
data={institutions}
renderItem={({ item }) =>
<InstitutionItem
title={item.name}
image={require('../../../assets/hands.jpg')}
logo={require('../../../assets/institution.png')}
location={item.address}
phone={item.phone}
email={item.email}
navigation={navigation}
id={item._id}
/>}
keyExtractor={(item, index) => index.toString()}
refreshing={refresh}
onRefresh={() => onRefresh()}
ListHeaderComponent={renderHeader}
/>
</SafeAreaView>
</View>
);
}
}
I tried your code, and it doesn't seem to be something related with the SearchBar, it works as it should outside of the FlatList. The problem that you are having is that you are losing the input focus for some reason on how you are "injecting" the SearchBar into the FlatList. So what I did, was to put the SearchBar right into the code, like this:
<FlatList
data={institutions}
keyExtractor={(item, index) => index.toString()}
refreshing={refresh}
onRefresh={() => onRefresh()}
ListHeaderComponent={
<SearchBar
lightTheme
clearIcon
onChangeText={handleSearch}
value={value}
placeholder='Buscar...' />
}
/>
and it worked, you are now able to keep writing without losing the focus.
This is not a bad solution, it's an easy solution, but if this is not very to your liking, you should try to find how you can insert any component in the header of the FlatList from a function or a const. Abrazo!

How to sort a flatlist in react native [duplicate]

This question already has an answer here:
Sorting react-native FlatList
(1 answer)
Closed 2 years ago.
I am working on a to do list app in react native, when a new item is added it goes directly to the last place and I will like every new object to go to the first place. To achieve this I tried adding a function that is supposed to sort the items but it the code doesnt make any changes. How can I sort these items in my to do list?
app.js
const [todos, setTodos] = useState([]);
const [addMode, setAddMode] = useState(false);
const [isReady, setIsReady] = useState(false);
const addTodoHandler = addTodos => {
if (addTodos.lenght === 0) {
return;
};
setTodos(prevTodos => [...prevTodos, { key: Math.random().toString(), value: addTodos, date: Date.now() }]);
setAddMode(false);
Keyboard.dismiss();
};
const sortTodos = () => { //this is the function that is supposed to sort the items.
const todoSort = [...todos];
const soarted = todoSort.sort((a, b) => {
return a.todoSort - b.todoSort;
})
setTodos(soarted);
};
return (
<View style={styles.screen}>
<Header />
<AddTodo onAddTodo={addTodoHandler} />
<FlatList
keyExtractor={(item, index) => item.key}
data={ todos }
renderItem={({ item }) => <TodoItem key={item.key}
todoKey={item.key}
title={item.value}
editHandler={handleEdit}
pressHandler={pressHandler}/> }
/>
</View>
);
AddTodo.js
const AddTodo = props => {
const [text, setText] = useState('');
const changeHandler = (val) => {
setText(val);
};
const addTodoHandler = () => {
props.onAddTodo(text);
setText('');
};
return (
<View style={styles.inputView}>
<TextInput style={styles.textInput} placeholder='What do you want to do?' onChangeText={changeHandler} value={text}/>
<Buttons title="Add" onPress={addTodoHandler} style={styles.salsachBtn}/>
</View>
);
};
TodoItem.js
const TodoItem = props => {
return (
<View>
<View style={styles.items}>
<View style={styles.itemContainer}>
<Text style={styles.itemText}>{props.title}</Text>
</View>
</View>
</View>
);
};
if you have any questions please let me know in the comments:)
First idea:
Add your 'sortTodos' inside function that handle adding new item.
Add date to items with e.g. Date.now()
Sort a.date - b.date
Second (without sorting): you can try to use unshift
const newTodo = [...prevTodos]
newTodo.unshift({ key: Math.random().toString(), value: addTodos });
setTodos(newTodo)

How to make the react native switch to true when list of toggle button is rendered through a map?

Problem:
I am rendering a set of toggle buttons through a map. Now I want to make it true or false each when the user is changing the value of each toggle. This is how I have created the toggle component.
const AnswerToggle = (props) => {
const {styles, name} = props;
return (
<View style={styles.answerContentContainer}>
<View style={styles.answerTextContainer}>
<AppText styles={styles.answerText}>{name}</AppText>
</View>
<View style={styles.container}>
<Switch
trackColor={{false: '#dddddd', true: '#c1d6ee'}}
thumbColor={{false: '#ffffff', true: '#007aff'}}
ios_backgroundColor="#dddddd"
// ref={name}
onValueChange={
(value) => {
// ref[name].value = true;
}
// console.log(
// '>>>>>> value',
// this[`${name}`].value,
// )
}
style={styles.toggle}
/>
</View>
</View>
);
};
And I am loading it through map like this.
return answers.map((answer, i) => {
return (
<AnswerToggle
key={i}
styles={styles}
name={name}
/>
);
});
I try to do it by giving reference to the Switch component. Then It says you cannot use ref without forwardRef so then I put it to the AnswerToggle component but it still giving me the error can some help me to solve this issue?. I tried lot to find out a solution to this problem. But I was unable to do so
Define the onChange handler in the parent component and pass it in as a prop. When the switch is flipped update the state in the parent accordingly and pass the new value to AnswerToggle as a prop.
// pseudo code
const [switchValues, setSwitchValues] = useState([]);
const onChange = (index, value) => setSwitchValues( ... );
answers.map((a, i) => <AnswerToggle value={switchValues[i]} onChange={newValue => onChange(i, newValue) />
This will work just fine:
const AnswerToggle = (props) => {
const {styles, name} = props;
const [toggleStatus, setToggle] = React.useState(false)
const onChange = () => setToggle(status => !status)
return (
<View style={styles.answerContentContainer}>
<View style={styles.answerTextContainer}>
<AppText styles={styles.answerText}>{name}</AppText>
</View>
<View style={styles.container}>
<Switch
trackColor={{false: '#dddddd', true: '#c1d6ee'}}
thumbColor={{false: '#ffffff', true: '#007aff'}}
ios_backgroundColor="#dddddd"
onChange={onChange}
value={toggleStatus}
style={styles.toggle}
/>
</View>
</View>
);
};
EDIT:
If you need to set the statuses of toggles into the parent component, this is my solution for you:
const AnswerToggle = (props) => {
const {styles, name, onChange, value} = props;
return (
<View style={styles.answerContentContainer}>
<View style={styles.answerTextContainer}>
<AppText styles={styles.answerText}>{name}</AppText>
</View>
<View style={styles.container}>
<Switch
trackColor={{false: '#dddddd', true: '#c1d6ee'}}
thumbColor={{false: '#ffffff', true: '#007aff'}}
ios_backgroundColor="#dddddd"
onChange={() => onChange(name)}
value={value}
style={styles.toggle}
/>
</View>
</View>
);
};
const Parent = props => {
// ... other code
// set all toggles to false
const [toggleStatuses, setToggle] = React.useState(
answers.reduce((toggles,answer) => {
toggles[answer.name] = false
return toggles
},{})
);
const onChange = name => setToggle(state => ({
...state,
[name]: !state[name],
}));
return answers.map((answer, i) => {
return (
<AnswerToggle
value={toggleStatuses[answer.name]}
onChange={onChange}
key={i}
styles={styles}
name={answer.name}
/>
);
});
}

Categories

Resources