Bind a object value into a component when TouchableOpacity Avatar pressed - javascript

My goal is to display the overlay bound to that button when the baby avatar is clicked.
Let me know how to fix it.
const OverlayForm = ({ baby }) => {
return <BabyProfile baby={baby} />;
}
return (
<React.Fragment>
<View style={styles.main}>
{Babies.map((baby: Baby, index) => (
<View>
<TouchableOpacity
style={styles.button}
onPress={() => {
toggleOverlay;
myValue = baby;
}}
key={index}
>
<AvatarData baby={baby} />
</TouchableOpacity>
</View>
))}
<Overlay isVisible={visible} onBackdropPress={toggleOverlay}>
{OverlayForm(myValue)}
</Overlay>
</View>
</React.Fragment>
);
}
I solved as this by Quentin Grisel's advice.

You should handle the overlay inside your Baby avatar component and simply change its state to display/hide the overlay.
export default function App() {
return <BabyAvatar overlay={false} />;
}
const BabyAvatar = () => {
const [isOverlayed, setIsOverlayed] = React.useState(false);
const displayOverlay = () => setIsOverlayed(!isOverlayed);
return (
<>
<Text>Baby overlay: {isOverlayed ? 'true':'false'}</Text>
<Button onPress={() => displayOverlay()} title="Change overlay" />
</>
)
}

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

const [item1, item2] inside class component (react-native)?

I've been working on a React-Native project.
For export default function App() INSERT 1 to 3 (on code) works.
For export default class App extends Component none of the INSERT's works.
I have to combine them since the modal gives the user the ability to insert text inside the modal and then process the data to console.log and from there use the data.
export default class App extends Component {
{/* INSERT 1 before render also gives error */}
render () {
{/* INSERT 1 */}
const [list, setList] = useState();
const HandleAddList = () => {
console.log(list);
{/* INSERT 1 END */}
return (
<View>
<Modal
animationType = {"slide"}
transparent={false}
visible={this.state.isVisible}>
<View style={styles.ModalContext}>
<View style={styles.ModalNavigation}>
<Text style={[styles.closeText, styles.navText]}
onPress={() => {
this.displayModal(!this.state.isVisible);
}
}> Cancel </Text>
<Text style = {[styles.navHeader, styles.navText] }>
New</Text>
<Text style={[styles.doneText, styles.navText]}
onPress={() => {
this.displayModal(!this.state.isVisible);
{/* INSERT 2 */}
HandleAddList();
{/* INSERT 2 */}
}
}> Done </Text>
</View>
<TextInput
style={styles.inputText}
placeholder='Enter Something...'
{/* INSERT 3 */}
value = {list}
onChangeText={text => setList(text)}
{/* INSERT 3 */}
autoFocus
/>
</View>
</Modal>
{/* Rest of the code */}
</View>
{/* const stylesheets etc. */}
React-native's documentation told me that I can't use const inside a class component. (https://reactjs.org/warnings/invalid-hook-call-warning.html).
INSERT-comments were only for the purpose of the question and testing was done without it...
All the needed modules was imported from 'react-native'
Any solutions? Would be grateful if someone can help...
You can't use Hooks on Class Components, it's only a Functional Components' feature. Instead of that you could use this,I'm not pretty sure about some things but you can fix the errors:
import styles from './styles.css'
export default function App() {
const [list, setList] = useState();
const [isVisible, setIsVisible] = useState(true);
const HandleAddList = () => {
console.log(list);
}
return (
<View>
<Modal
animationType={"slide"}
transparent={false}
visible={isVisible}>
<View style={styles.ModalContext}>
<View style={styles.ModalNavigation}>
<Text style={[styles.closeText, styles.navText]}
onPress={() => {
setIsVisible(!isVisible);
}
}> Cancel </Text>
<Text style={[styles.navHeader, styles.navText]}>
New</Text>
<Text style={[styles.doneText, styles.navText]}
onPress={() => {
setIsVisible(!isVisible);
HandleAddList();
}
}> Done </Text>
</View>
<TextInput
style={styles.inputText}
placeholder='Enter Something...'
value={list}
onChangeText={text => setList(text)}
autoFocus
/>
</View>
</Modal>
</View>
)
}
I'm not used to Class Components, but I think this can guide you:
export default class App extends Component {
constructor() {
super()
this.state = {
isVisible: true,
list: ""
}
}
HandleAddList () {
console.log(this.state.list);
}
render () {
return (
<View>
<Modal
animationType={"slide"}
transparent={false}
visible={this.state.isVisible}>
<View style={styles.ModalContext}>
<View style={styles.ModalNavigation}>
<Text style={[styles.closeText, styles.navText]}
onPress={() => {
this.setState({...this.state, isVisible: !this.state.isVisible});
}
}> Cancel </Text>
<Text style={[styles.navHeader, styles.navText]}>
New</Text>
<Text style={[styles.doneText, styles.navText]}
onPress={() => {
this.setState({...this.state, isVisible: !this.state.isVisible});
this.HandleAddList();
}
}> Done </Text>
</View>
<TextInput
style={styles.inputText}
placeholder='Enter Something...'
value={this.state.list}
onChangeText={text => this.setState({ ...this.state, list: text})}
autoFocus
/>
</View>
</Modal>
</View>
)
}
}
It's so important you read the documentation (https://es.reactjs.org/docs/state-and-lifecycle.html) by yourself, there's a pair of things here you could fix reading it. It's a pleasure to help anyway, hope this works for you.

Change useState's from remote component

I know with the following code below changing a useState within another component's onPress event wouldn't be possible but how would I do it? I want to make it so when the onPress function within Card.js is executed the popUpData from within App.js is changed.
App.js
const [popUpData, setPopUpData] = React.useState("Nothing")
return (
<Card>
<Text style={styles.pokemonName}>{item.name}</Text>
</Card>
<Text>{popUpData}</Text>
)
Card.js
const doSomething = () => {
setPopUpData("Something")
//other things...
}
return (
<TouchableOpacity activeOpacity={1} style={styles.card} onPress={doSomething()}>
<View style={styles.cardContent}>
{ props.children }
</View>
</TouchableOpacity>
)
App.js
const [popUpData, setPopUpData] = React.useState("Nothing")
return (
<Card onUpdate={(d)=>setPopUpData(d) }>
<Text style={styles.pokemonName}>{item.name}</Text>
</Card>
<Text>{popUpData}</Text>
)
Card.js
function Card(props){
const doSomething = () => {
props.onUpdate("Something")
}
return (
<TouchableOpacity activeOpacity={1} style={styles.card} onPress={doSomething()}>
<View style={styles.cardContent}>
{ props.children }
</View>
</TouchableOpacity>
)
}
Just pass reference to setState function down to child component.
(in the simplest scenario)
const Parent = () => {
const [popUpData, setPopUpData] = React.useState("Nothing")
return (
<Card setPopUpDataHandler={setPopUpData}>
<Text style={styles.pokemonName}>{item.name}</Text>
</Card>
<Text>{popUpData}</Text>
)
}
const Card = ({setPopUpDataHandler, children}) => {
const doSomething = () => {
setPopUpDataHandler("Something")
//other things...
}
return (
<TouchableOpacity activeOpacity={1} style={styles.card} onPress={doSomething()}>
<View style={styles.cardContent}>
{ children }
</View>
</TouchableOpacity>
)
}

Changing style of specific component returned from map function onClick

I am trying to change the style of individual TouchableOpacity components that have been returned from a map function.
Here is the component:
Example = ({ props }) => {
return (
<View>
{props.listExample.map(({ id }) => {
return (
<React.Fragment key={id}>
<TouchableOpacity
style={styles.button}
onPress={() => console.log(id)}>
<Image source={require('example.jpg')} />
</TouchableOpacity>
</React.Fragment>
);
})}
</View>
);
};
Let TouchableOpacity = TO.
The map function returns about 30 TOs with unique IDs. When I click the TOs, I can see their unique ID in the console log. I want to know how I can modify the style of an individual TO.
Here is my render function which uses the functional component Example.
render() {
return (
<View style={styles.body}>
<ScrollView>
<View style={styles.column}>
<this.Example props={{ listExample: this.getList() }} />
</View>
</ScrollView>
</View>
);
}
What I have tried:
referencing this stackoverflow post, I tried to create a function which changed the style of the TO when it is clicked. But the result of this changed all the TOs in the UI since of the way it is mapped.
I tried something like the following.
Example = ({ props }) => {
return (
<View>
{props.listExample.map(({ id }) => {
let buttonStyle = this.state.pressed ? styles.button : styles.buttonClicked
return (
<React.Fragment key={id}>
<TouchableOpacity
style={buttonStyle}
onPress={() => console.log(id)}>
<Image source={require('example.jpg')} />
</TouchableOpacity>
</React.Fragment>
);
})}
</View>
);
};
But as previously stated, this changed all of the Touchable Opacitys. Is there a way to only change one?
Thanks
Edit - to show entire class
class Page extends Component {
constructor(props) {
super(props)
}
MyButton = ({ onButtonPressed = () => {} }) => {
const [isPressed, setIsPressed] = useState(false);
const onPressed = () => {
setIsPressed(!isPressed);
onButtonPressed();
}
return (<TouchableOpacity style={isPressed ? styles.pressedButton: styles.button}
onPress={onPressed}>
<Image source={require('example.jpg')} />
</TouchableOpacity>
);
}
Example = ({ props }) => {
return (
<View>
{props.listExample.map(({ id }) => {
return (
<MyButton key={id}/>
);
})}
</View>
);
};
render() {
return (
<View style={styles.body}>
<ScrollView>
<View style={styles.column}>
<this.Example props={{ listExample: this.getList()}} />
</View>
</ScrollView>
</View>
);
}
}
It is easier to separate the component inside map to a separate component and then handle style changes on press there
const MyButton = ({ onButtonPressed = () => {} }) => {
const [isPressed, setIsPressed] = useState(false);
const onPressed = () => {
setIsPressed(!isPressed);
onButtonPressed();
}
return (<TouchableOpacity style={isPressed ? styles.pressedButton: styles.button}
onPress={onPressed}>
<Image source={require('example.jpg')} />
</TouchableOpacity>
)
}
so you can use in the map like this
Example = ({ props }) => {
return (
<View>
{props.listExample.map(({ id }) => {
return (
<MyButton key={id} />
);
})}
</View>
);
};

How to use ReactNative FlatList ScrolltoIndex properly?

I'm a newbie in react native and I'm running into an issue I didn't manage to solve by myself.
So far this is how I am using it:
export default class Form extends React.Component {
state = {index: 0};
_keyExtractor = (item, index) => item.id;
myscrollToIndex = () => {
this.setState({index: ++this.state.index});
this.flatListRef.scrollToIndex({animated: true,index: this.state.index});
};
_renderItem = ({item}) => (
<View>
<Question {...item} />
<Button label='Next' onPress={this.myscrollToIndex} style={styles.buttonNext}/>
</View>
)
render() {
return (
<View style={styles.container}>
<FlatList
horizontal={false}
ref={(ref) => { this.flatListRef = ref; }}
scrollEnabled
data={this.props.form}
extraData={this.state}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem} />
</View>
);
}
}
I would like to pass the index to myscrolltoindex function but I don't manage to as this.flatListRef gets ruled out when I do that.
Have anyone run into a similar issue ?
Thank you for your time
Use index param as well. And pass the index around.
For e.g _renderItem = ({item, index}) => ( <View> <Question {...item} /> <Button label='Next' onPress={this.myscrollToIndex(index) } style={styles.buttonNext}/> </View> )

Categories

Resources