I hope you already have installed or set up an android studio, emulator, or expo in your machine, I will go through the coding part.
First of all open your command then install the react-native
npx react-native init AwesomeProject
now run your project with the command react-native run-android
(if IOS then react-native run-ios
)
know more details from here
now you have all the important files, find the App.js
file and remove all code from here
import React, {useState} from 'react';
import { StyleSheet, Text, View, Button, TextInput, ScrollView } from 'react-native';
add those two lines in the App.js
file
Then I just adding all code after that I will explain step by step:
import React, {useState} from 'react';
import {
StyleSheet,
Text,
View,
Button,
TextInput,
ScrollView,
} from 'react-native';
const App = () => {
const [enterGoal, setEnterGoal] = useState('');
const [courseGoals, setCourseGoals] = useState([]);
const goalInputHandler = enteredText => {
setEnterGoal(enteredText);
};
const addGoalHandler = () => {
setCourseGoals(currentGoals => [...currentGoals, enterGoal]);
// setEnterGoal('');
};
return (
<View style={styles.screen}>
<View style={styles.inputcontainer}>
<TextInput
style={styles.input}
placeholder="Course Goal"
onChangeText={goalInputHandler}
value={enterGoal}
/>
<Button title="ADD" onPress={addGoalHandler} />
</View>
<ScrollView>
{courseGoals.map(goal => (
<Text style={styles.listItem} key={goal}>
{goal}
</Text>
))}
</ScrollView>
</View>
);
};
const styles = StyleSheet.create({
screen: {
padding: 50,
},
inputcontainer: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
input: {
borderColor: 'black',
borderWidth: 1,
padding: 10,
width: '80%',
},
listItem: {
padding: 10,
backgroundColor: '#ccc',
borderColor: 'black',
borderWidth: 1,
marginVertical: 10,
},
});
export default App;
I have added a TextInput
which is imported from react-native
for user input, here is styles.input
for a simple design with CSS
<TextInput
style={styles.input}
placeholder="Course Goal"
onChangeText={goalInputHandler}
value={enterGoal}
/>
setEnterGoal
will store data from the value={enterGoal}
<Button title="ADD" onPress={addGoalHandler} />
If the user will press on the ADD button then fire addGoalHandler
function which will contain
const addGoalHandler = () => {
setCourseGoals(currentGoals => [...currentGoals, enterGoal]);
// setEnterGoal('');
};
If you use setEnterGoal('')
then after every ADD input fill will clear
Now we have all data inside courseGoals
So, now we can mapping those data using,
<ScrollView>
{courseGoals.map(goal => (
<Text style={styles.listItem} key={goal}>
{goal}
</Text>
))}
</ScrollView>
I have used ScrollView
from react-native
for scrolling
here is the final output.
here is the full source code