Git Product home page Git Product logo

rajinwonderland / react-code-blocks Goto Github PK

View Code? Open in Web Editor NEW
584.0 8.0 81.0 165.54 MB

React code blocks and code snippet components

Home Page: https://react-code-blocks.rajinwonderland.vercel.app

License: MIT License

JavaScript 6.67% CSS 8.85% TypeScript 83.08% MDX 1.40%
react-components prismjs hljs highlightjs syntax-highlighting remark mdx syntax-theme react-codemirror react-codemirror2

react-code-blocks's Introduction

All Contributors

Welcome to react-code-blocks ๐Ÿ‘‹๐Ÿ‘‹๐Ÿ‘‹

Version Downloads Documentation License: MIT Twitter: rajinwonderland

React components for rendering code snippets with syntax highlighting

BREAKING CHANGES: VERSION >= ^0.1.0 has not been tested with Node 14 or lower

Background

Initially, this started as a small project looking to modify Atlaskit's Code Block component to support more languages (i.e graphql, reasonml, etc). It then rapidly evolved into a never-ending rabbithole which ended up with support for themes (i.e railscast, darcula, monokai, etc), customizable styles, and copy functionality too. Contributions are welcome via PRs and issues.

โœจ Storybook

Check out react-code-blocks

Install

Install react-code-blocks

npm i react-code-blocks

Usage

Updated usage instructions can be found here

import { CopyBlock } from "react-code-blocks";
function MyCodeComponent(props) {
  const copyBlockProps = {
    text: props.code,
    language: props.language,
    showLineNumbers: props.showLineNumbers,
    startingLineNumber: props.startingLineNumber,
    wrapLines: true,
  };

  return (
    <CopyBlock
      {...copyBlockProps}
    />
  );
}

Components

CodeBlock

A simple code block component

import { CodeBlock, dracula } from "react-code-blocks";

function MyCoolCodeBlock({ code, language, showLineNumbers, startingLineNumber }) {
  return (
    <CodeBlock
      text={code}
      language={language}
      showLineNumbers={showLineNumbers}
      startingLineNumber={startingLineNumber}
      theme={dracula}
    />
  );
}

Props

Note that CodeBlock & CopyBlock share exactly the same props

name type default description
text string required The code to be formatted
language string "text" The language in which the code is written. See here for a list of supported languages
showLineNumbers boolean true Indicates whether or not to show line numbers
startingLineNumber number 1 if showLineNumbers is enabled the line numbering will start from here.
theme object dracula A theme object for the code block. See here for a list of supported themes
highlight string "" Lines to highlight! For multiple lines, use a comma i.e highlight="1,6,7". For a range of lines, use a - i.e highlight="1-5" for highlighting lines 1-5.

more to come...

CopyBlock

A code block component with a little copy button for copying a snippet.

import { CopyBlock, dracula } from "react-code-blocks";

function MyCoolCodeBlock({ code, language, showLineNumbers, startingLineNumber }) {
  <CopyBlock
    text={code}
    language={language}
    showLineNumbers={showLineNumbers}
    startingLineNumber={startingLineNumber}
    theme={dracula}
    codeBlock
  />;
}

Props

Same as the CodeBlock's component with the exception of one!

name type default description
codeBlock boolean false Indicates whether to render the CopyBlock as an inline Code component or a CodeBlock component

Supported Themes

For a list of supported themes, check out the list here

Supported Languages

For a list of supported languages, check out the list here

Alternatives

If you're looking for some more maintained solutions, I'd suggest the following:

  • react-syntax-highlighter: syntax highlighting component for react with prismjs or highlightjs ast using inline styles by @conorhastings.
    • It's actually used in this project as well! ๐Ÿ˜„
  • react-highlight.js: A lightweight React wrapper around the Highlight.js syntax highlighting library by @bvaughn.
  • react-live: A flexible playground for live editing React components by @FormidableLabs.
  • @atlaskit/code: Renders inline code snippets and code blocks
    • Original inspiration for this project kit for this project
  • carbon-components-react: Check out their <CodeSnippet> component which supports multi-line, single-line, and inline snippets along with added copying functionality.

Feel free to add any other alternative packages here! ๐Ÿ˜„

Todos

  • Add a better readme
  • Highlighting line feature
  • Supported Themes documentation
  • Supported Languages documentation
  • Add a License
  • Docs for usage with GatsbyJS
  • Docs for usage with MDX
  • Contributor guide for development
  • Contributor guide for adding themes
  • Contributor guide for adding languages
  • Document props for Code component
  • Better demo
  • Storybook with Docs
  • Move to typescript
  • A component with a terminal around it. because why not!? ๐Ÿง

Show your support

Give a โญ๏ธ if this project helped you!


This README was generated with โค๏ธ by readme-md-generator

Author


Taha HICHRI

๐Ÿ’ป

florpor

๐Ÿ›

Abdollah Keshtkar

๐Ÿ’ก ๐Ÿ“– ๐Ÿ’ป

Lukas Bals

๐Ÿ’ป

Bobby Wang

๐Ÿ’ป

Matthew Peveler

๐Ÿ“–

Dacey Nolan

๐Ÿ’ก ๐Ÿ“– ๐Ÿ’ป

Kevin Eaton

๐Ÿ’ป

This project follows the all-contributors specification. Contributions of any kind welcome!

react-code-blocks's People

Contributors

allcontributors[bot] avatar azrosen92 avatar bofeiw avatar cannonlock avatar cromartin avatar daceynolan avatar dependabot[bot] avatar dht avatar florpor avatar hamadtheironside avatar kevineaton603 avatar lukasbals avatar masterodin avatar mavaddat avatar okeeffed avatar rajinwonderland avatar rohit-ravikoti avatar suyashpatil78 avatar tahahichri avatar tahoedesigner avatar tang8330 avatar thomasmost avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-code-blocks's Issues

Vulnerability of dependency

Thank you for the great package,
I have noticed that Prismjs has v 1.23 is marked as hight vulnerability,
image
This was patched in v1.24 can the react-code-blocks be updated to use the latest prism version ? thank you

Alignment issue when combining CopyBlock and showLineNumbers

Version: [email protected]
React Version: [email protected]
Browser: Chrome/79.0.3945.88 (Mac OS 10.15)

First of all, great project - exactly what I was looking for!

Unfortunately, when setting showLineNumbers={true} on a CopyBlock, the whole block gets knocked down to below the line numbers.

Screenshot 2020-01-06 at 16 46 24

Code used (after using create-react-app and removing most of the default css styles):

//App.css
.App {
  width: 800px;
  margin: 0 auto;
  margin-top: 30px;
}
//App.js
import React from 'react';
import './App.css';
import { CopyBlock, dracula } from 'react-code-blocks'

const javascriptSnippet = `function toBe() {
  if (Math.random() < 0.5) {
    return true;
  } else {
    return false;
  }
}`;

function App() {
  return (
    <div className="App">
      <CopyBlock
        language='javascript'
        showLineNumbers={true}
        text={javascriptSnippet}
        theme={dracula}
      />
    </div>
  );
}

export default App;

Language shell not supported

I tried creating a CopyBlock with the language set to shell but I get this error (in dev and prod): Uncaught (in promise) Error: Language shell not supported
I saw in the supported languages there is the shell language so I think this is a bug.

Cannot read 'textColor' of undefined

Problem statement

Seems like theme is undefined. This is the error received when trying to use the component:

Screen Shot 2022-05-24 at 3 08 12 PM

<CopyBlock
    text={...}
    language={"typescript"}
    theme={dracula}
    showLineNumbers
    codeBlock
/>

Correctly associate MIT license on npm

Hello,

Thank you for the hard work that has been put into this library.

The library has an MIT license on GitHub, but on the npm is listed as having no license. As a result this is causing our internal tooling to reject onboarding this library for consumption in our organisation. Can you kindly address this?

Thank you!

Clickable Link

Hi. Is it possible to add an actual clickable link to the code string?

const code = const instagram = 'https://www.instagram.com/didemk95/'; const a = <a href=\"http://www.example.com\">here</a>

I want them to be clickable

Contributing to the project

Hey @rajinwonderland
So I've been using your component in my Gatsby/MDX project and I love it.
I would love to contribute to the gatsby and how to use it section.

thanks for your awesome repo, I really appreciate it

Feature: Props component

Can you make a props component please. I am building something similar to material-ui. I want a Props component to display the props of the component.

wrapLines & wrapLongLines Not working.

I've observed an issue regarding the wrapping of content to the next line, tried by using both wrapLines & wrapLongLines but it didn't solved that.
What I found: The Span inside the CodeBlock div have a property (white-space: pre;) which is not updating to (white-space: normal;).

Can't overwrite styles in production with tailwindcss

I tried to overwrite the existing styles with tailwindcss like this

.react-syntax-highlighter-line-number {
  @apply text-[#607B96];
}

code .token {
  @apply text-[#607B96] !important;
}

.efofCE {
  @apply bg-transparent p-0 !important;
}

.efofCE span {
  @apply bg-transparent !important;
}

.sc-bcXHqe.kBPKLM {
  @apply hidden !important;
}

And this is the result in develop.
image

This is the result in production (vercel).
image

how to fix this?

Codesandbox Demo is Broken -> Requires React 16.11

This is an awesome project, thanks for making it. Just wanted to give you a heads up the codesandbox demo is broken, you just need to change package.json to point to a more recent version of react. (I changed it to 16.8 for example and it worked)

Screen Shot 2019-11-02 at 5 53 06 PM

Language html is not supported

I am trying to use a code block with html (which is supported according to supported languages), but it gives me the following error:

async-syntax-highlighter.js:110 Uncaught (in promise) Error: Language html not supported
at Function._callee$ (async-syntax-highlighter.js:110)
at tryCatch (runtime.js:45)
at Generator.invoke [as _invoke] (runtime.js:274)
at Generator.prototype. [as next] (runtime.js:97)
at asyncGeneratorStep (asyncToGenerator.js:3)
at _next (asyncToGenerator.js:25)
at asyncToGenerator.js:32
at new Promise ()
at Function. (asyncToGenerator.js:21)
at Function.loadLanguage (async-syntax-highlighter.js:121)
at ReactAsyncHighlighter.loadLanguage (async-syntax-highlighter.js:67)
at ReactAsyncHighlighter.componentDidMount (async-syntax-highlighter.js:53)
at commitLifeCycles (react-dom.development.js:19814)
at commitLayoutEffects (react-dom.development.js:22803)
at HTMLUnknownElement.callCallback (react-dom.development.js:188)
at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
at invokeGuardedCallback (react-dom.development.js:292)
at commitRootImpl (react-dom.development.js:22541)
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority$1 (react-dom.development.js:11039)
at commitRoot (react-dom.development.js:22381)
at finishSyncRender (react-dom.development.js:21807)
at performSyncWorkOnRoot (react-dom.development.js:21793)
at react-dom.development.js:11089
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority$1 (react-dom.development.js:11039)
at flushSyncCallbackQueueImpl (react-dom.development.js:11084)
at flushSyncCallbackQueue (react-dom.development.js:11072)
at flushPassiveEffectsImpl (react-dom.development.js:22883)
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority$1 (react-dom.development.js:11039)
at flushPassiveEffects (react-dom.development.js:22820)
at react-dom.development.js:22699
at workLoop (scheduler.development.js:597)
at flushWork (scheduler.development.js:552)
at MessagePort.performWorkUntilDeadline (scheduler.development.js:164)

here is my implementation

<CopyBlock text={code} language="html" showLineNumbers={true} theme={dracula} wrapLines codeBlock />

Error: Language html not supported

[email protected]

Downloaded this library because it looked great for the project I'm working on. Unfortunately ran into this error:

Screen Shot 2020-12-09 at 11 37 43 AM

For now I can use the language 'jsx' for what I need to do but it would be nice to have 'html' available. I tried 'html5' and 'HTML' just incase it was a name thing or something but nothing worked.

Softwrap long lines

Hi, it'll be good if I can soft-wrap long code in a line by passing in a parameter like softWrap={true}.

Currently I need to write custom css to implement soft-wrap. It works but nice to add in this feature.

code {
  max-width: 90%;
  overflow-wrap: break-word;
}

I am getting Error and not working with react js v 18 -

I am not getting any Error message after adding the packages .
`
npm WARN deprecated [email protected]: Version no longer supported. Upgrade to @latest

added 28 packages, and audited 1137 packages in 9s

176 packages are looking for funding
run npm fund for details

6 vulnerabilities (5 moderate, 1 high)

Some issues need review, and may require choosing
a different dependency.
`

into code file.

`

`

Right side padding prop

Hello and thanks for the library :)

I need to write long ugly one line script and it gets overlaid by copy button. Maybe it would make sense to add option to break code before reaching copy button or moving button outside of container. I solved this using padding in customStyle but I find that to be hacky and I think this is legit concern for long lines as rare as they are (should be).

Edge of one line also overflowed outside of container.
image
I do not know what the cause is here as last span does not seem to actually overflow. Here with white background:
image

Build outputs a build file for each language in React Project.

When building a react project with react-code-blocks, the build output includes a build file for each supported language even if one language is used.

Build Output

This doesn't occur if directly importing for react-syntax-highlighter.

Expected Behavior:
Only include build file for languages being used in project.

Code block rendering inline-block in .tsx

I'm using @vercel to ship a pretty simple .tsx app and for some reason, it renders as inline instead of code block. Here's my code:

const toggleCodeTheme = (window.innerWidth) < 1000 ? hybrid : github;
<CopyBlock language="javascript" text={iterative} codeBlock theme={toggleCodeTheme} showLineNumbers={false} />

Need way to constrain height / add a scrollbar

By default it appears that it expands to the code snippet's entire length. This is not ideal for large snippets of code you need to place inside a block while still making the webpage look nice.

Uncaught ReferenceError: global is not defined

core.js:221
Uncaught ReferenceError: global is not defined
at capture (core.js:221:28)
at node_modules/react-code-blocks/node_modules/refractor/core.js (core.js:5:15)
at __require2 (chunk-62VDRKYJ.js?v=20a5b317:19:50)
at prism-light.js:2:23

Error: Language html not supported

I see it says html is a supported language, but I'm getting an error when trying to use it with a CopyBlock

Seems to happen when I have improper syntax in the code block. Test with the following (missing quote)

<a href="https://google.com>Hello World</a>
Node v10.8.0
[email protected]
react ^16.12.0

Typed Props in Exported Components

Issue:
The Themed Components are exported at the package level but do not include typed props. TS throws compile errors because we are accessing "unsafe/undefined" properties of the components.

Text is not selectable when using highlight

Hello! Love the component and especially the highlight feature. However, when using the highlight prop, text becomes not selectable.

Works fine with the normal component:
image

However, I cannot select any text when highlighting a line:
image

Would be amazing to see a fix for this.

Error: Language cs not supported

I used the below code. I tried both language csharp and cs. There is an error in the dev version but the style is still applied for the code block.
In the build production version, the error is still there but there is no style for code. How can I fix this?

<CopyBlock
   language='csharp'
   text={codeString}
   wrapLines
   showLineNumbers
   theme={sunburst}
   codeBlock
 ></CopyBlock>

image

Language xml not supported

Hi there, I just noticed there's error pops up when language is xml. However xml is a supported language listed here, can anyone help with this? Thank you!

image

Line numbers issue

Hi, I have an issue with line numbers.

It is probably a bug.

<CopyBlock
  text={'var a = 10;\nconsole.log(a);'}
  language="javascript"
  theme="dracula"
  wrapLines
  codeBlock
/>
<span linenumbercontainerstyle="[object Object]"></span>

Warning: React does not recognize the lineNumberContainerStyle prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase linenumbercontainerstyle instead. If you accidentally passed it from a parent component, remove it from the DOM element.

There is a white background behind text and clipboard icon is too small

This is how the UI is looking

image

Below is my code I used

      text={`function toBe() {
            if (Math.random() < 0.5) {
              return true;
            } else {
              return false;
            }
            }`}
      showLineNumbers={true}
      codeBlock
      language="text"
      theme={a11yDark}
      customStyle={{
        height: "250px",
        width: "100%",
        overflowY: "scroll",
        borderRadius: "5px",
        boxShadow: "1px 2px 3px rgba(0,0,0,0.35)",
        fontSize: "3.75rem",
        margin: "0px 0.75rem",
      }}
    />```


**I tried changing themes and tried in custom styles also but it didn't work**

Support for types for CodeBlock and CopyBlock.

I would like to have support for prop types for components such as CodeBlock and CopyBlock using TypeScript. Is there any way to provide types for these components?

I want to implement like this:

type Props = CodeBlockProps;
const Example: React.FC<Props> = (props: Props) => {
 return (
  <CodeBlock {...props} language="jsx" />
  );
}

this not working with my react native app!!

this not properly working with my react native app he got error in my android application "s.default.button is not a function. (In 's.default.button(k(),(function(e){return e.theme.backgroundColor}),(function(e){return e.copied?1:.5}))', 's.default.button' is undefined)"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.