React Markdown not render properly in React - javascript

I am creating dev.to clone for react js practice when
trying to render markdown in react-markdown it doesn't render properly,
here it is:
Post.js
import React, { useState } from 'react';
import ReactMarkdown from 'react-markdown';
import SyntexHighlight from '../../components/SyntexHighlight';
const Post = ({ post }: any) => {
return (
<main className="h-full bg-white rounded-md border">
<header>
.........
</header>
<div
className=" leading-8 marker:text-black max-w-2xl mx-auto py-6 prose
prose-lg prose-p:block prose-li:py-[0.5] prose-li:my-0 prose-a:text-blue-600
hover:prose-a:text-blue-500 prose-code:text-sm prose-code:bg-gray-200
prose-code:p-1 prose-code:rounded prose-img:mx-auto "
>
<ReactMarkdown components={SyntexHighlight}>{post.body}</ReactMarkdown>
</div>
<section className="border-t-2 px-8 py-4">
........
</section>
</main>
);
};
export default Post;
SyntexHighlight.js
import React from 'react';
import { Prism } from 'react-syntax-highlighter';
import { oneDark } from 'react-syntax-highlighter/dist/cjs/styles/prism';
const SyntexHighlight = {
code({ node, inline, className, ...props }: any) {
const match = /language-(\w+)/.exec(className || '');
return !inline && match ? (
<Prism style={oneDark} language={match[1]} PreTag="div" className="codeStyle" {...props} />
) : (
<code className={className} {...props} />
);
},
};
export default SyntexHighlight;
It doesn't render properly
markdown render problem
markdown render problem
markdown render problem
I tried "json2md" package after getting JSON string form node server still not working
when i try "json2md" data to separate variable
data variable
<div
className=" leading-8 marker:text-black max-w-2xl mx-auto py-6 prose
prose-lg prose-p:block prose-li:py-[0.5] prose-li:my-0 prose-a:text-blue-600
hover:prose-a:text-blue-500 prose-code:text-sm prose-code:bg-gray-200
prose-code:p-1 prose-code:rounded prose-img:mx-auto "
>
<ReactMarkdown components={SyntexHighlight}>{MarkdownFile}</ReactMarkdown>
</div>
Now its working properly
it's working
it's working
it's working
i don't know what is the problem ???

Related

Why is useEffect from React not being called?

I don't understand why my useEffect is not being called? I'm following a Youtube tutorial right now and all my code looks exactly the same as in the video. I was reading this: useEffect not being called and not updating state when api is fetched but I couldn't relate it to my problem so I was wondering if anyone could help me on this.
Thanks so much.
import { useSession } from "next-auth/react";
import { ChevronDownIcon } from "#heroicons/react/outline";
import { useEffect, useState } from "react";
import { shuffle } from "lodash";
const colors = [
"from-indigo-500",
"from-blue-500",
"from-green-500",
"from-red-500",
"from-yellow-500",
"from-pink-500",
"from-purple-500",
];
function Center() {
const { data: session } = useSession();
const [color, setColor] = useState(null);
useEffect(() => {
console.log("useEffect called");
setColor(shuffle(colors).pop());
}, []);
return (
<div className="flex-grow">
<header className="absolute top-5 right-8">
<div className="flex items-center bg-red-300 space-x-3 opacity-90 hover:opacity-80 cursor-pointer rounded-full p-1 pr-2">
<img
className="rounded-full w-10 h-10"
src={session?.user.image}
alt=""
/>
<h2>{session?.user.name}</h2>
<ChevronDownIcon className="h-5 w-5" />
</div>
</header>
<section
className={
"flex items-end space-x-7 bg-gradient-to-b to-black ${colors} h-80 text-white padding-8"
}
>
<h1>hello</h1>
</section>
</div>
);
}
export default Center;
MRE:
import { useEffect, useState } from "react";
const colors = [
"from-indigo-500",
"from-blue-500",
"from-green-500",
"from-red-500",
"from-yellow-500",
"from-pink-500",
"from-purple-500",
];
function Center() {
const [color, setColor] = useState(null);
useEffect(() => {
console.log("useEffect called");
}, []);
return (
<div className="flex-grow">
<section
className={
"flex items-end space-x-7 bg-gradient-to-b to-black ${colors} h-80 text-white padding-8"
}
>
</section>
</div>
);
}
export default Center;
FINALLY SOLVED!!!
${colors} should've been ${color} and everything in className={} needs to be surrounded by `` not "". I originally thought useEffect() wasn't even been called because I was looking at VSCode terminal instead of chrome console.
Maybe sounds obvious, but are you sure you didn't filter out your console log from chrome developer tools? The default shows info, warnings and errors but I often filter one and next time I open the console have to reset it.

Why am i getting this error "react Invalid hook call. Hooks can only be called inside of the body of a function component" in the following code?

import React,{ useEffect, useState} from 'react';
import { useLocation } from 'react-router-dom';
import ReactPlayer from 'react-player';
import { useResultContext } from '../contexts/ResultContextProvider';
export const Results = () => {
const {getResults, results, isLoading, searchTerm} = useResultContext();
const location = useLocation();
const [num, setNum] = useState(10);
const changeNum=()=>{
setNum(num+10);
console.log(num)
Results();
}
useEffect(()=>{
if(searchTerm){
if (location.pathname ==='/videos') {
getResults(`/search/q=${searchTerm} videos&num=${num}`)
}else{
getResults(`${location.pathname}/q=${searchTerm}&num=${num}`)
}
}
},[location.pathname, searchTerm, num, getResults]);
switch (location.pathname) {
case '/search':
return (<><div className='flex flex-wrap justify-between space-y-6 sm:px-56 overflow-hidden pb-4 '>
{
results?.results?.map(({link, title, description}, index)=>(
<div key={index} className='md:w-3/5 w-full'>
<a href={link} target="_blank" rel="noreferrer">
<p className='text-sm text-green-700'>
{link.length>50? link.substring(0,50): link}
</p>
<p className='text-lg hover:underline dark:text-blue-300 text-blue-700'>
{title}
</p>
</a>
{description.length>15?
<p>
{description}
</p>:''}
</div>
))
}
</div>
<div onClick={changeNum} className='absolute bg-gray-200 border border-gray-400 py-3 px-10 rounded-full -mt-5 left-96 cursor-pointer active:bg-gray-300 dark:bg-gray-700 '>
More Results
</div>
</>);
default: return 'ERROR';
}
};
I've started learning react and it's been two days i have been unable to get around this.
I'm trying to make google search engine clone and in this project i'm getting results using google search api and displaying 10 results at first and want then to increase by 10 every time when i click on 'More Results' button which calls 'changeNum' function which uses 'setNum' to add 10 value to 'num' every time function is called by clicking on button.
EDIT: i shortened the code by removing some cases
const changeNum=()=>{
setNum(num+10);
console.log(num)
Results(); <--------
}
Calling your functional component like this is what is causing the error. This line is not needed as your component will update when you update the state.

add block-input from sanity.io to next.js blog post

I'm developing a blog on next.js with sanity.io, and I'm having trouble using the code-input plugin.
What I do have
I'm able to use the code component block on sanity, which looks something like this:
Everything good on the sanity side. My problem comes with using it on the next.js [slug].js file.
I have this error prompt out:
This issue with this is that I don't have a serializer.js file/component anywhere on my code, not even on the studio root folder. I've seen this applies for gatsby but I don't know how to apply it for Next.js
This is what I currently Have:
import groq from 'groq'
import imageUrlBuilder from '#sanity/image-url'
import BlockContent from '#sanity/block-content-to-react'
import client from '../../client'
import Layout from '../../components/layout'
import utilStyles from '../../styles/utils.module.css'
import styles from '../../components/layout.module.css'
function urlFor (source) {
return imageUrlBuilder(client).image(source)
}
const Post = (props) => {
const {
title = 'Missing title',
name = 'Missing name',
categories,
authorImage,
mainImage,
code,
body = []
} = props
console.log(props)
return (
<Layout>
<article>
<div className={styles.container}>
<figure>
<img src={urlFor(mainImage).url()} />
</figure>
<h1 className={utilStyles.headingXl}>{title}</h1>
{categories && (
<ul className="inline">
Category:
{categories.map(category =>
<li key={category}>
<span className="inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-indigo-100 bg-indigo-700 rounded">{category}</span>
</li>)}
</ul>
)}
<BlockContent
blocks={body}
imageOptions={{fit: 'max'}}
{...client.config()}
{...code}
/>
</div>
</article>
</Layout>
)
}
const query = groq ` *[_type == "post" && slug.current == $slug][0]{
title,
"name": author->name,
"categories": categories[]->title,
mainImage,
code,
"authorImage": author->image,
body,
}`
Post.getInitialProps = async function(context) {
const {slug = ""} = context.query
return await client.fetch(query, { slug })
}
export default Post
I really would appreciate some help here! Thanks <3
You can pass a serializer for the code block type to your BlockContent using the serializers prop.
const serializers = {
types: {
code: props => (
<pre data-language={props.node.language}>
<code>{props.node.code}</code>
</pre>
)
}
}
// ...
<BlockContent
blocks={body}
imageOptions={{fit: 'max'}}
{...client.config()}
{...code}
serializers={serializers}
/>

TypeError: Cannot read property after refresh or after manipulation

I am getting the following error after a refresh and sometimes on initial project run:
TypeError: Cannot read property 'statements' of undefined
This is really confusing because the data is rendering fine it just seems the connection fails. Any idea what may be causing the error?
There are no additional errors when I remove the statements.map
I used this medium article to get everything up and running: Medium Article
index.js:
import React, { useState, useReducer } from 'react'
import { useQuery } from '#apollo/react-hooks'
// Custom layout
import Layout from "../components/layout"
import '../sass/styles.scss'
// Data Query
import STATEMENTS_QUERY from '../graphql/statements'
function StatementCall(context) {
const { loading, error, data } = useQuery(STATEMENTS_QUERY, {});
return (
<Layout>
<div className="container">
<div className="row spaces">
<div className="col-md-12">
<p>Testing</p>
{data.statements.data.map((statement, index) => (
<div>
<p>{statement.id}</p>
<p>{statement.title}</p>
</div>
))}
</div>
</div>
</div>
</Layout>
)
}
export default StatementCall
graphql/statements.js:
import gql from 'graphql-tag';
const STATEMENTS_QUERY = gql`
query {
statements(filter: {destination: 1991}) {
data {
id
title
body
}
}
}
`;
export default STATEMENTS_QUERY;
You could check if the results are loading, before you try to render them.
Example:
function StatementCall(context) {
const { loading, error, data } = useQuery(STATEMENTS_QUERY, {});
if (loading) {
return <p>Loading...</p>;
}
if (error) {
// Handle error?
return <p>{error}</p>;
}
return (
<Layout>
<div className="container">
<div className="row spaces">
<div className="col-md-12">
<p>Testing</p>
{data.statements.data.map((statement, index) => (
<div>
<p>{statement.id}</p>
<p>{statement.title}</p>
</div>
))}
</div>
</div>
</div>
</Layout>
)
}
Check the example in useQuery docs.

Learning React Beautiful DnD basics without building Trello Clone

I want to learn React Beautiful Dnd by coding two div boxes that contain child elements I can drag between them. All (most?) tutorials online are Trello clones with loops and state that clutter my understanding of the basics. I want to simplify my understanding by hard coding only the most minimal state required with the end result being two components (the component name is "Column") each that contain a div (A component named "Task") that I can drag to the other.
At the moment. I am getting the error " TypeError: children is not a function ".
Here is my code:
src/App.js
import {DragDropContext} from 'react-beautiful-dnd';
import Column from './Components/Column';
function App() {
return (
<DragDropContext onDropEnd={result => console.log("my life is worth more than this")}>
<Column id="1"/>
</DragDropContext>
);
}
export default App;
src/Components/Column
import React from 'react';
import {Droppable} from 'react-beautiful-dnd';
import Task from "../../Components/Task"
function Column(props){
const { classes, id } = props;
let style = {
backgroundColor:"orange",
height:"100px",
width:"100px",
margin:"100px"
}
return (
<Droppable droppable = {id}>
{provided => (
<div {...provided.droppableProps} ref={provided.innerRef} style={style}>
Column is orange task is red
<Task id="1"/>
<Task id="2"/>
{provided.placeholder}
</div>
)
}
</Droppable>
)
}
export default Column
src/Components/Task
import React from 'react';
import {Draggable} from 'react-beautiful-dnd';
function Task(props){
const { classes, id } = props;
return (
<Draggable draggableId ={id}>
<div>
some task
</div>
</Draggable>
)
}
export default Task
Here is a basic working example of simply dragging items (in case anyone is looking for it). I've decided to document my learning here because I feel remedial examples are lacking in the official docs. I like "hello world" examples.
The first thing to realize is that using the library requires understanding three components. Each component has it's respective boilerplate code.
They are (buried down the page) in the official docs.
<DragDropContext />
- Wraps the part of your application you want to have drag and drop enabled for
<Droppable />
- An area that can be dropped into. Contains components
<Draggable />
- What can be dragged around
Your app needs to be wrapped in a single DragDropContext (multiple DragDropContext are not supported). This example has minimal state.The id properties in the state objects are required (they can be named different but are required none the less).
src/App.js
import React,{useState} from 'react';
import {DragDropContext} from 'react-beautiful-dnd';
import Column from './Components/Column';
function App() {
const [listOne, setListOne] = useState([{id:"1", title:"Test-1"},{id:"2", title:"Test-2"}]);
const [listTwo, setListTwo] = useState([{id:"3", title:"Test-3"},{id:"4", title:"Test-4"}]);
return (
<DragDropContext onDropEnd={result => console.log(result)}>
<Column id="1" list = {listOne}/>
<Column id="2" list = {listTwo}/>
<div> context hello world </div>
</DragDropContext>
);
}
export default App;
<Droppable/> components nest <Draggable/> components. This returned function boiler plate code is required:
{provided => (
)}
Explanation for each property of provided is here
src/Components/Column
import React from 'react';
import {Droppable} from 'react-beautiful-dnd';
import Task from "../../Components/Task"
function Column(props){
const { classes, id, list } = props;
let style = {
backgroundColor:"orange",
height:"300px",
width:"400px",
margin:"100px"
}
console.log(list)
return (
<Droppable droppableId = {id}>
{provided => (
<div {...provided.droppableProps} ref={provided.innerRef} style={style}>
{list.map((val,index)=>{
return <Task id={val.id} key={index} index={index} title={val.title}/>
})}
{provided.placeholder}
</div>
)
}
</Droppable>
)
}
export default Column
src/Components/Task
import React from 'react';
import {Draggable} from 'react-beautiful-dnd';
function Task(props){
const { classes, id, index,title } = props;
let style = {
backgroundColor:"red",
}
return (
<Draggable draggableId ={id} index={index} >
{(provided) => (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
<h4 style={style}>{title}</h4>
</div>
)}
</Draggable>
)
}
export default Task

Categories