react native
2025-03-25 - Workshop React native
import { Button, TextInput } from "react-native";
import { React, useCallback, useState, useEffect } from "react";
const url = "https://mocki.io/v1/5b86c4eb-61f7-4175-b6d0-29ba3a48245a";
function App() {
const [names, setNames] = useState<String>([]);
const list = names.map((name) => <li>{name}</li>);
const reverseNames = useCallback(() => {
// You must create another array.
setNames((names) => [...names].reverse());
}, []);
const [newName, setNewName] = useState("");
const onNewNameChange = useCallback((newName) => setNewName(newName), []);
// No need for useCallback here, otherwise, the function will be memoized with the initial value of `names`.
const addName = function () {
setNames((names) => [...names, newName]);
};
const fetchNames = async () => {
try {
const response = await fetch(url);
const json = await response.json();
setNames(json.names);
} catch (error) {
console.error(error);
}
};
useEffect(() => {
fetchNames();
}, []);
return (
<>
<ul>{list}</ul>
<ReverseButton onPress={reverseNames} />
<AddName
newName={newName}
onNewNameChange={onNewNameChange}
onPress={addName}
/>
</>
);
}
function ReverseButton({ onPress }) {
return (
<>
<Button title="Reverse name" color="black" onPress={onPress} />
</>
);
}
function AddName({ newName, onNewNameChange, onPress }) {
console.log(newName);
return (
<>
<TextInput value={newName} onChangeText={onNewNameChange} />
<Button title="Add new name" onPress={onPress} />
</>
);
}
export default App;