soccerway
soccerway

Reputation: 11991

How to add code block for code snippets for in the data displays in the react hooks page

I am displaying blog contents from contentful in my react hooks website. Now the full description of blog is received in post.description. I would like to display code snippets, json data received in post.description as code block. Also would like to add the head lines to h1 or h2 tag. How can we identify the code block from description field ? Now it just displays the text in the page ( please refer the screen shot added )

import React from "react";
import { Link, useParams } from "react-router-dom";
import MD from "react-markdown";
import { useSinglePost } from "../custom-hooks";
import Moment from 'moment';



export default function SinglePost() {
  const { id } = useParams();
  const [post, isLoading] = useSinglePost(id);

  const renderPost = () => {
    if (isLoading) return ( <div> <p className="noSearchData">Loading...</p> </div>);

    return (
      <React.Fragment>
        <div className="main_intro">
          <h3 className="blog_title">{post.title}</h3>
          <small className="blog_date">{Moment(post.createdAt).format('MMM DD YYYY')}</small>
          <pre className="blog_main_desc"><code>{post.description}</code></pre>
          <img
            className="blog_img"
            src={post.image.fields.file.url}
            alt={post.title}
          />
        </div>

        <div className="post__body">
          <MD source={post.body} />
        </div>
      </React.Fragment>
    );
  };

  return (
    <div className="post">
      <Link className="post__back" to="/">
        {"< Back"}
      </Link>

      {renderPost()}
    </div>
  );
}

enter image description here

enter image description here

Upvotes: 0

Views: 3655

Answers (1)

Arv
Arv

Reputation: 467

To include the code snippet as a block of code in ReactJs you could use a syntax highlighter like react-syntax-highlighter

install npm react-syntax-highlighter --save

And then in your code import the highlighter:

import SyntaxHighLighter from 'react-syntax-highlighter';
import { dracula } from 'react-syntax-highlighter/dist/cjs/styles/hljs';

<SyntaxHighLighter language="javascript" style={dracula}>
{
    "class HelloMessage extends React.Component {\n render() {\n return ( \n <div>\nHello {this.props.name}\n</div>\n);\n }\n}\n\nReactDOM.render(\n<HelloMessage name='Taylor' />,\ndocument.getElementById('hello-example')\n);"
  }
</SyntaxHighLighter>

Upvotes: 5

Related Questions