Open In App

Create a Blog App using React-Native

Last Updated : 07 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This article shows how to create a basic blog app using react native. This app contains functionalities such as adding a blog and a delete button to remove the blogs using react native. The user can enter content with a title and then click on ‘Add New Post’ to create a new blog post

Preview of final output: Let us have a look at how the final output will look like.

blog-app

Prerequisites:

Approach:

In this code, we’re crafting a basic React Native application for a blog. It empowers users to peruse a catalog of blog posts, select a post to read, and insert fresh content into the catalog. Deleting existing posts is also a feature. The code smartly checks for input validity, ensuring that new posts must have both a title and content, and not be left empty. It harnesses various React Native elements like View, Text, TextInput, Button, and FlatList to present the blog posts and manage user interactions. For a polished and organized look, the styling is meticulously handled through StyleSheet.

Steps to Create React Native Application:

Step 1: Create a react native application by using this command

npx create-expo-app calculator-app-in-native

Step 2: After creating your project folder, i.e. calculator-app-in-native, use the following command to navigate to it:

cd calculator-app-in-native

Project Structure:

reactnativeProj

Project Structure

Example: Write the following code in App.js file.

Javascript




import React, { useState } from 'react';
import {
    View, Button, TextInput, Text,
    FlatList, StyleSheet, TouchableOpacity
} from 'react-native';
 
const data = [
    {
        id: 1, title: 'React',
        content: `ReactJS is a declarative, efficient, and flexible
                JavaScript library for building user interfaces.` },
    {
        id: 2, title: 'React Native',
        content: `React Native: It is a framework developed
                by Facebook for creating native-style apps
                for iOS & Android.` },
    // Add more blog posts here
];
 
const App = () => {
    const [selectedPost, setSelectedPost] = useState(null);
    const [newPostTitle, setNewPostTitle] = useState('');
    const [newPostContent, setNewPostContent] = useState('');
    const [posts, setPosts] = useState(data);
    const [error, setError] = useState('');
 
    const addNewPost = () => {
        if (newPostTitle.trim() === '' ||
            newPostContent.trim() === '') {
            setError('Title and content cannot be empty');
            return;
        } else {
            setError('');
        }
 
        const id = posts.length + 1;
        const newPost =
        {
            id, title: newPostTitle,
            content: newPostContent
        };
        setPosts([...posts, newPost]);
        setNewPostTitle('');
        setNewPostContent('');
    };
 
    const deletePost = (postId) => {
        const updatedPosts =
            posts.filter(
                (post) =>
                    post.id !== postId);
        setPosts(updatedPosts);
    };
 
    const renderItem = ({ item }) => (
        <TouchableOpacity
            onPress={() => setSelectedPost(item)}>
            <View style={styles.postContainer}>
                <Text style={styles.postTitle}>
                    {item.title}
                </Text>
                <Text style={styles.postContent}>
                    {item.content}
                </Text>
                <TouchableOpacity style={styles.deleteButton}
                    onPress={() => deletePost(item.id)}>
                    <Text style={styles.deleteButtonText}>
                        Delete
                    </Text>
                </TouchableOpacity>
            </View>
        </TouchableOpacity>
    );
 
    return (
        <View style={styles.container}>
            <View style={styles.headingContainer}>
                <Text style={styles.heading}>Blog App</Text>
            </View>
            {!selectedPost ? (
                <FlatList
                    data={posts}
                    renderItem={renderItem}
                    keyExtractor={(item) => item.id.toString()}
                />
            ) : (
                <View style={styles.selectedPostContainer}>
                    <Text style={styles.selectedPostTitle}>
                        {selectedPost.title}
                    </Text>
                    <Text style={styles.selectedPostContent}>
                        {selectedPost.content}
                    </Text>
                    <TouchableOpacity style={styles.backButton}
                        onPress={() => setSelectedPost(null)}>
                        <Text style={styles.backButtonText}>
                            Back
                        </Text>
                    </TouchableOpacity>
                </View>
            )}
            {selectedPost === null && (
                <View style={styles.formContainer}>
                    {error !== '' &&
                        <Text style={styles.errorText}>
                            {error}
                        </Text>}
                    <TextInput
                        style={styles.input}
                        placeholder="Enter Title"
                        value={newPostTitle}
                        onChangeText={setNewPostTitle}
                    />
                    <TextInput
                        style={[styles.input, styles.textArea]}
                        placeholder="Enter Content"
                        value={newPostContent}
                        onChangeText={setNewPostContent}
                        multiline={true}
                    />
                    <Button title="Add New Post"
                        onPress={() => addNewPost()} />
                </View>
            )}
        </View>
    );
};
 
const styles = StyleSheet.create({
    container: {
        flex: 1,
        paddingTop: 40,
        paddingHorizontal: 20,
    },
    headingContainer: {
        backgroundColor: '#3498db',
        padding: 10,
        borderRadius: 10,
        marginBottom: 20,
    },
    heading: {
        fontSize: 24,
        fontWeight: 'bold',
        textAlign: 'center',
        color: 'white',
    },
    postContainer: {
        borderWidth: 1,
        borderColor: '#ccc',
        padding: 20,
        marginBottom: 20,
        borderRadius: 10,
    },
    postTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        marginBottom: 10,
    },
    postContent: {
        fontSize: 16,
    },
    deleteButton: {
        alignSelf: 'flex-end',
        marginTop: 10,
    },
    deleteButtonText: {
        color: 'red',
    },
    selectedPostContainer: {
        padding: 20,
        marginBottom: 20,
        borderWidth: 1,
        borderColor: '#ccc',
        borderRadius: 10,
    },
    selectedPostTitle: {
        fontSize: 24,
        fontWeight: 'bold',
        marginBottom: 10,
    },
    selectedPostContent: {
        fontSize: 16,
    },
    backButton: {
        alignSelf: 'flex-end',
        marginTop: 20,
    },
    backButtonText: {
        color: 'blue',
        fontSize: 16,
    },
    formContainer: {
        padding: 20,
        borderWidth: 1,
        borderColor: '#ccc',
        borderRadius: 10,
        marginBottom: 20,
    },
    input: {
        borderWidth: 1,
        borderColor: '#ccc',
        padding: 10,
        marginBottom: 10,
        borderRadius: 5,
    },
    textArea: {
        height: 100,
    },
    errorText: {
        color: 'red',
        textAlign: 'center',
        marginBottom: 10,
    },
});
 
export default App;


Steps to Run the react native application

Step 1 : Write the following command in terminal

npx expo start

Step 2: Depending on your operating system type the following commmand

  • To run on Android
npx react-native run-android
  • To run on IOS
npx react-native run-ios

Output:

blog



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads