Beginner’s Guide to React Native Development

Code your first app with a from concept to code guide

Are you searching for a technology to develop mobile applications but don’t know where to start? Your search ends here. In this article, we will learn about React Native, how it works, and why to use it.

What is React Native ?

React Native is an open-source framework developed by Facebook that allows developers to build mobile applications using JavaScript and React. React Native enables developers to write a single codebase that can be used to create apps for both iOS and Android. This not only saves time but also simplifies maintenance and updates.

You might be wondering: what is the difference between React and React Native? The main difference between them in web applications is that React Native uses native components compiled into native code. This means that apps built in React Native are truly native applications. Their code syntax is similar but under the hood, things work differently. We are not going further into the inner workings of React Native right now because this is a subject for another article in the future. For now, all we need to know is that React and React Native have similar code syntax, and if you are already familiar with Javascript and React, this will not be challenging to learn.

"So, if I already know React concepts, will I be able to develop React Native applications?" Yes, this is one of the advantages of choosing React Native: the learning curve is less steep if you already know React.

Alright, let’s get started!

First of all, we will need Node.js with npm (Node Package Manager) installed so we can install Expo. "Okay, I already know Node.js, but what is Expo?" Expo is an open-source framework recommended in React Native Documentation. Nothing better than the Expo Documentation itself to explain this to us:

“Expo brings together the best of mobile and the web and enables many important features for building and scaling an app such as live updates, instantly sharing your app and web support. The expo npm package enables a suite of incredible features for React Native apps. The expo package can be installed in nearly any React Native project.”

Now that we have Expo installed, we can run npx create-expo-app my-app to create our first mobile app. Navigate to the project repository cd my-app and run npx expo start. There it goes, your first React Native is already running! We now have two options: use the Expo Go app on your smartphone or an emulator. What is Expo Go? Let’s go back to the documentation: “Expo Go is a free, open-source client for testing React Native apps on Android and iOS devices without building anything locally. It allows you to open up apps served through Expo CLI and run your projects faster when developing them.” Very simple and very easy. However, I’d recommend becoming familiar with emulators if you want to work with React Native. Why? Sometimes we may need to test our application on various screen sizes or different Android/iOS versions without having access to physical devices, or when we don’t want to install these apps on our own smartphones. Last but not least, we frequently have to demonstrate features or issues to our colleagues and clients, and the emulator is a better way to do it since you can record or share your screen easily. Install Android Studio or Xcode for macOS and follow the steps in the documentation to configure your emulator in your respective OS.

What’s next?

Now that we have our development environment properly configured and our first application running we need to know better how to use this tool. React Native documentation brings the components we can use to make an application. Let’s implement a To-Do list app to get familiar with these components. To make the To-do list more complex, we will add another feature in which we add a button to start/pause and finish the task. In this way, we can see how much time we spend on each task at the end of the day.

On the App.js file, we will add the states responsible for registering our tasks:

const [tasks, setTasks] = useState([]);
const [currentTask, setCurrentTask] = useState('');

Then we add our addTask function:

const addTask = () => {
  if (currentTask !== ' ') {
     setTasks([...tasks, { id: Date.now(), text: currentTask }]);
     setCurrentTask('');
  }
};

So far, so good. Now we return to our main component:

return (
<View style={styles.container}>
    <TextInput
    style={styles.input}
    value={currentTask}
    onChangeText={text => setCurrentTask(text)}
    placeholder="Type a new task"
    />
    <Button title="Add Task" onPress={addTask} />
    {tasks.map(task => (
        <Task id={task.id} text={task.text} style={styles.task}/>
    ))}
</View>
);

There are three important components here from React Native. The first one is the View, let’s see what the documentation says about it:

“View is a container that supports layout with flexbox, style, some touch handling, and accessibility controls. View maps directly to the native view equivalent on whatever platform React Native is running on, whether that is a UIView, div, android.view, etc.”

The TextInput is equivalent to input, and the Button to an HTML button.

Last but not least, our Stylesheet component:

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
        padding: 20,
    },
    input: {
        height: 40,
        width: '100%',
        borderColor: 'gray',
        borderWidth: 1,
        marginBottom: 10,
        paddingHorizontal: 10,
    },
    task: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        width: '100%',
        marginTop: 10,
        backgroundColor:'#F5F5F5'
    },
});

A StyleSheet is an abstraction similar to CSS and we can send the attributes via props in our components.
We also have a Task component which is a custom Component we will create now.
Let’s make a components directory to keep Task on it:

Inside the components directory, we will create a Task.js file. Our Task component will look like this:

const Task = ({ id, text, style }) => {
    const [done, setDone] = useState(false);

    const finishTask = () => {
        setDone(true);
    };
    return (
    <View key={id} style={style}>
    <Text>{text}</Text>
    {done ? (
    <Text>Done !</Text>
    ) : (
    <TouchableOpacity onPress={finishTask}>
        <Text>Finish Task</Text>
    </TouchableOpacity>
    )}
    </View>
    );
};

The TouchableOpacity is a component with functionality similar to that of the Button, but it allows you to wrap other components within it.

Now let’s add a timer to each task. On Task.js we will add a StopWatch component, which will receive a boolean to stop the timer:

<StopWatch stop={done}/>

On our components directory we will add the StopWatch.js and its code will look like this:

const StopWatch = ({stop}) => {
    const [elapsedTime, setElapsedTime] = useState(0);
    const [active, setActive] = useState(false);

    useEffect(() => {
        let interval;
        if (active) {
            interval = setInterval(() => {
            setElapsedTime((prevTime) => prevTime + 1);
        }, 1000);
        } else {
            clearInterval(interval);
    }

    return () => {
        clearInterval(interval);
    };
    }, [active]);

    useEffect(() => {
        if (stop) {
            setActive(false);
        }
    }, [stop]);

    const toggleWatch = () => {
        setActive(!active);
    };
    return (
    <>
        <Text>
            Time: {Math.floor(elapsedTime / 60).toString().padStart(2, "0")}:{(elapsedTime % 60).toString().padStart(2, "0")}
        </Text>
        <TouchableOpacity onPress={toggleWatch} disabled={stop}>
            <Text>{active ? "Pause" : "Start"} Task</Text>
        </TouchableOpacity>
    </>
);
};

That’s it. Our app will look like this:

The UI needs some improvement. I will encourage you to do the UI styling as a challenge. Explore the StyleSheet component and feel free to customize the UI as you want.

Congratulations! You have built a basic React Native app. Now that you know the fundamentals of React Native and how to use its core components, you should be able to explore more complex resources within this technology. I recommend this repository to get good app ideas: https://github.com/florinpop17/app-ideas. It offers options ranging from beginner-level apps to more advanced projects. Some of these ideas require you to know how to consume data from APIs in React Native. So, stay tuned because a new post on this theme is coming soon!

References

React Native Documentation
Expo Documentation
NodeJs Documentation

We want to work with you. Check out our "What We Do" section!