Error when trying to pass image source from a component to its child component - react-native

I'm currently creating a small example of React Native. The issue I'm having is that when I tried to pass the image source from my LoginScreen component to ImageHolder component, the Node shows error below:
Loading dependency graph, done.
error: bundling failed: Error: src\ImageHolder.js:Invalid call at line 7: require({
imageSource: imageSource
})
at C:\Users\Kuro\vuichoi_ui\node_modules\metro\src\JSTransformer\worker.js:247:19
at Generator.next (<anonymous>)
at step (C:\Users\Kuro\vuichoi_ui\node_modules\metro\src\JSTransformer\worker.js:40:30)
at C:\Users\Kuro\vuichoi_ui\node_modules\metro\src\JSTransformer\worker.js:51:15
Here is my code:
LoginScreen.js render:
render() {
if (true) {
return (
<View>
<LoginText
imgSource="./img/account.png"
secureOption={false}
value={this.state.username}
placeholder="username"
onChangeText={username => this.setState(username)}
/>
</View>
)
}
}
LoginText.js:
const LoginText = ({imgSource, secureOption, placeholder, value, onChangeText}) => {
return (
<View style={styles.containerStyle}>
<ImageHolder imageSource={imgSource} />
<InputField placeholder={placeholder} secureOption={secureOption} value={value} onChangeText={onChangeText}/>
</View>
)
}
ImageHolder.js:
const ImageHolder = ({imageSource}) => {
return (
<View style={styles.imgContainerStyle}>
<Image source={require(imageSource)}></Image>
</View>
)
}

The issue is in the path of Image. If all the component on the same path then you can the same thing.
The solutions is that you need to pass Image from LoginScreen.js
render() {
if (true) {
return (
<View>
<LoginText
imgSource={require('./img/account.png')}
secureOption={false}
value={this.state.username}
placeholder="username"
onChangeText={username => this.setState(username)}
/>
</View>
)
}
}
ImageHolder.js
const ImageHolder = ({imageSource}) => {
return (
<View style={styles.imgContainerStyle}>
<Image source={imageSource}></Image>
</View>
)
}
Replace the code above tow js and it will work for you.

Related

nothing was returned from render but can't be fixed

I don't know what I did wrong in this function, I thought I had a return but I don't think it's being considered, and when I change the closing brackets or parenthesis it shows an error :/
Can someone help me?
function PopSheet() {
let popupRef = React.createRef()
const sheet =() => {
const onShowPopup =()=> {
popupRef.show()
}
const onClosePopup =()=> {
popupRef.close()
}
return (
<SafeAreaView style ={styles.container}>
<TouchableWithoutFeedback onPress={onShowPopup}>
</TouchableWithoutFeedback>
<BottomPopup
title="Demo Popup"
ref ={(target) => popupRef =target}/>
onTouchOutside={onClosePopup}
</SafeAreaView>
);
}
};
You need to use the render function which is responsible for rendering or display the JSX element into your app.
render() {
return (
<SafeAreaView style={styles.container}>
<TouchableWithoutFeedback
onPress={onShowPopup}></TouchableWithoutFeedback>
<BottomPopup title="Demo Popup" ref={target => (popupRef = target)} />
onTouchOutside={onClosePopup}
</SafeAreaView>
);
}

Strange behavior using useState to load data into a object state

i have broken my head trying to understand a problem with my code. I'm new with React Native so there may be a standard behavior that i am unaware of. This is my problem:
In my component i have a useEffect() to load my data like "componentDidMount":
useEffect( () => {
async function loadDadosLista(){
let listaRecebida = await getListaByID(route.params.idLista);
setLista(listaRecebida);
};
loadDadosLista();
}, []);
My function works correctly, the function getListaById accesses my realm.db and return my object lista. After that I can access the data and associate it with components of type TextInput. My real problem is that any change the i do in any component using properties of lista, overwrites all data leaving only the one that has been modified. I'm using spread operator but apparently it doesn't work. Below is my complete code for better understanding.
function ListConfig(){
const [lista, setLista] = useState({});
useEffect( () => {
async function loadDadosLista(){
let listaRecebida = await getListaByID(route.params.idLista);
setLista(listaRecebida);
};
loadDadosLista();
}, []);
return(
<View style={styles.container}>
<View style={[styles.containerLinha, styles.linha2]}>
<View style={styles.inputLocal}>
<TextInput
name='estabelecimento'
placeholder='Venda do seu Francisco'
placeholderTextColor={theme.colors.cinzaPrimario}
style={styles.textInputLocal(theme)}
value={lista.estabelecimento}
maxLength={25}
onChangeText={ (value) => {
setLista({
...lista,
estabelecimento: value
})
}}
textAlignVertical='bottom'
/>
<IconLocation width={20} height={24} />
</View>
</View>
<View style={styles.containerNotif}>
<Text style={styles.textoNotif(theme)}>
Me notifique 20 minutos antes
</Text>
<ToggleSwitch
isOn={lista.notificacaoAtiva}
onColor={theme.colors.cinzaSecundario}
offColor={theme.colors.cinzaSecundario}
thumbOnStyle={{
backgroundColor: theme.colors.destaque
}}
size="medium"
onToggle={(isOn) => {
setLista({
...lista,
notificacaoAtiva: isOn
});
}}
/>
</View>
</View>
);
}
export default ListConfig;
My object lista have this properties:
{
estabelecimento: 'nameOfEstabelecimento',
notificacaoAtiva: true
}

ListItem not showing information - React Native Elements

When I use it works fine.
But when I try to use , nothing appears.
That's my code:
export default props => {
//console.warn(Object.keys(props))
function getUserItem({item: user}) {
console.warn(user.name)
return (
<ListItem
leftAvatar={{source: {uri: user.avatarUrl}}}
key={user.id}
title={user.name}
/>
)
}
return (
<View>
<FlatList
keyExtractor={user=>user.id.toString()}
data={users}
renderItem={getUserItem}
/>
</View>
)
}
Can anybody helps me? Thank you!!!
Use this way
<View style={{flex:1}}>
...
</View>
const getUserItem = ({item: user}) => {
...
}

React Native: change component colour using TouchableOpacity onPress()

I'm making a to-do list to display on a page where the user can click on an icon to mark the task as done, in which the background colour of the corresponding task changes. The issue I'm having is I reuse the 'task' component and cannot specify which component's background should change colour. Hence, clicking any of the icons changes only one component's background colour. GIF of what I mean is below:
Only one component is changing
My code is as follows:
export default function GoalItems(props) {
const goals = props.goals;
if (goals == 1) {
return <Goal goal="Goal 1" />;
} else if (goals == 2) {
return (
<View>
<Goal goal="Goal 1" />
<View style={{marginVertical: 15}} />
<Goal goal="Goal 2" />
</View>
);
} else {
return (
<View>
<Goal goal="Goal 1" />
<View style={{marginVertical: 15}} />
<Goal goal="Goal 2" />
<View style={{marginVertical: 15}} />
<Goal goal="Goal 3" />
</View>
);
}
}
function Goal(props) {
const text = props.goal;
const [checkBox, setCheckBox] = useState(false);
const [checkBoxValue, setCheckBoxValue] = useState(
'ios-checkmark-circle-outline',
);
const [iconColour, setIconColour] = useState('#FF1744');
const [goalColour, setGoalColour] = useState('#64B5F6');
onPressCheckBox = () => {
setCheckBox(!checkBox);
if (checkBox) {
setCheckBoxValue('ios-checkmark-circle');
setIconColour('#1ABC9C');
setGoalColour('#1ABC9C');
} else {
setCheckBoxValue('ios-checkmark-circle-outline');
setIconColour('#FF1744');
setGoalColour('#64B5F6');
}
};
return (
<View style={styles.goalContainer}>
<View style={[{backgroundColor: goalColour}, styles.goal]}>
<Text style={styles.text}>{text}</Text>
</View>
<TouchableOpacity onPress={() => this.onPressCheckBox()}>
<Icon
name={checkBoxValue}
size={40}
style={styles.checkbox}
color={iconColour}
/>
</TouchableOpacity>
</View>
);
}
And the I just render <GoalItems goals={num_of_goals} /> in my main app page. I know its poorly coded with the if statements but I'm not sure how to return X amount of <GoalItems /> given num_of_goals, but that's a separate issue...
Any advice would be appreciated. Thanks in advance!
i think the reason is asynchronous.
When you call setCheckBox(!checkBox) you must wait to it working. When it done, you continue handle new state.
onPressCheckBox = () => {
setCheckBox(!checkBox)
};
useEffect(() => {
if (checkBox) {
setCheckBoxValue('ios-checkmark-circle');
setIconColour('#1ABC9C');
setGoalColour('#1ABC9C');
} else {
setCheckBoxValue('ios-checkmark-circle-outline');
setIconColour('#FF1744');
setGoalColour('#64B5F6');
}
}, [])

react-native-elements checkbox update value

I have the following code and for some reason the checkbox is not updated when I click on them. Does anyone know what might be the problem? I am using CheckBox from react-native-elements. The checked property is based on whether a value exists in a set. The onpress function updates the state variable and I am able to get the correct values from the state variable. Thanks!
constructor(props) {
super(props);
this.state = {
interests: new Set(),
brands: new Set(),
medicalCondition: new Set(),
errorMessage: '',
loading: false
}
}
onPressHandler = (event, value, keyName) => {
let tempCheckedValues = new Set(this.state[keyName]);
tempCheckedValues.has(value) ? tempCheckedValues.delete(value) : tempCheckedValues.add(value);
console.log(tempCheckedValues);
this.setState({[keyName] : tempCheckedValues});
}
renderCheckboxGroup = (checkboxList, keyName) => {
return checkboxList.map((value, index) => {
return (
<CheckBox
key={index}
title={value}
onPress={(event) => this.onPressHandler(event, value, keyName)}
checked={this.state[keyName].has(value.toLowerCase())}
/>
)
})
}
render() {
const interestsConst = ["Tennis", "Golf", "Shopping", "Movie", "Hiking", "Reading", "Diving", "Investing"];
const brandsConst = ["Chanel", "Louis Vuitton", "H&M", "ZARA", "Hermes", "Gucci", "Cartier", "Burberry", "Nike", "Adidas", "Lululemon", "Athleta"];
const medicalConditionConst = ["Hypertension", "Hyperlipidemia", "Diabetes", "Back pain", "Anxiety", "Asthma", "Cancer", "Depression", "Shingles"];
return (
<View style={styles.container}>
<ScrollView>
<View style={styles.cardGroup}>
<Card title='Interests'>
{this.renderCheckboxGroup(interestsConst, 'interests')}
</Card>
</View>
<View style={styles.cardGroup}>
<Card title='Brands'>
{this.renderCheckboxGroup(brandsConst, 'brands')}
</Card>
</View>
<View style={styles.cardGroup}>
<Card title='Medical Conditions'>
{this.renderCheckboxGroup(medicalConditionConst, 'medicalCondition')}
</Card>
</View>
</ScrollView>
</View>
)
}
}