React Blog Example

You will find the information helpful if you are looking for a basic react blog example to use as a starting point.

React, a JavaScript library for building user interfaces has gained immense popularity and is now a cornerstone of modern web application development. Its component-based architecture, dynamic rendering, and seamless data handling have made it a favorite among developers. If you want to level up your React skills or embark on a new project, you’re in the right place.

The example project can is based on create react app. It uses React router and MUI 5. It also uses typescript.

Below is a snippet of one of the primary functions of the react blog example:

function ViewFullPost() {

  const [post, setPost] = React.useState<Post | null>(null);

  const params = useParams();

  React.useEffect(() => {

    const postByURL = posts.find((post) => {
      return post.url === params.id;
    });

    if (postByURL) {
      document.title = postByURL.title;
      document.getElementsByName('description')[0].setAttribute('content', postByURL.description);
      setPost(postByURL);
    }

  }, [params.id]);


  return (
      <Box sx={{
        display: 'flex',
        flexDirection: 'row',
        flexWrap: 'wrap',
        justifyContent: 'flex-start',
        alignItems: 'flex-start',
        padding: 2,
      }}>

        {post && <FullPost {...post} />}

        {/* TODO Display error / redirect to 404 page if post is null */}

      </Box>
  );
}

The ViewFullPost function looks for the id in the URL using react router. It will find it in the list of posts and set it in the state. The title and meta description are set in the DOM for SEO purposes.

export function ViewAllPosts() {
  return (
      <Box sx={{
        display: 'flex',
        flexDirection: 'row',
        flexWrap: 'wrap',
        justifyContent: 'flex-start',
        alignItems: 'flex-start',
        padding: 2,
      }}>

        {posts.map((post) => {
          return <PostCard key={post.title} {...post} />;
        })}

      </Box>
  );
}

The above code example will use an array of posts and render them with just the summary content.

This project does not have any tests added yet. Follow the link if you would like to learn how to write good unit tests in React.

To download a full example based on the react create app, you can go to this GitHub repo.

Similar Posts