How to auto-indent code string in PrismJS? NextJs APP - javascript

i am trying to use PrimsJs in a react project, my objetive is create a static template page, and add snippets, i am not sure if is the best option(primsjs) but i am trying to auto-indent the code, because actually my code is rendered in one line
THIS IS MY PAGE
import { MainLayout } from "../components/layouts/MainLayout";
import { Hero1, Hero1Code} from "../theme/blocks/hero/Hero1";
export default function Home() {
return (
<MainLayout>
<h1>Home Page</h1>
<Hero1 />
<Hero1Code />
</MainLayout>
);
}
THIS IS MY PRIMSJS COMPONENT
import React, { useEffect } from "react";
import Prism from "prismjs";
import "prismjs/themes/prism-tomorrow.css";
export default function Code({ code, language }) {
useEffect(() => {
Prism.highlightAll();
}, []);
return (
<div className="Code">
<pre>
<code className={`language-${language}`}>{code}</code>
</pre>
</div>
);
}
THIS IS MY COMPONENT
import React from "react";
import { renderToString } from "react-dom/server";
import Code from "../../../components/prism/code";
export const Hero1 = () => {
return (
<section className="wrapper bg-light">
...
</section>
);
};
export const Hero1Code = () => {
const content = renderToString(<Hero1/>);
return (
<>
<div className="App">
<Code code={content} language="html" />
</div>
</>
);
};
Any help will be very welcome, also i am open to try other package

I don't think that PrismJS has such an option, in my opinion it would be best to just indent the code string before passing it to the <Code /> component.
You could use this library: https://github.com/zebzhao/indent.js
Import it:
import indent from 'indent.js';
And indent the code like this:
const content = indent.html(renderToString(<Hero1/>));
However, looking at your screenshot code example, I can see that you have a lot of divs smashed into one line. In this case, indentation would not really help, as it takes care of the relations between separate lines.
You could take a look at using a library like this, which seems to split code into separate lines.
https://www.npmjs.com/package/pretty

Related

Conditional css in react/Next js

I am using Next js,I am applying conditional on component which is working,but css style changes between different component.
Code 1:
import React from "react";
import Profile from "../../components/model/Profile";
import { useAuthContext, useAuthUpdateContext } from "../../app/AuthContext"
function profile() {
const user = useAuthContext()
const { updateUser } = useAuthUpdateContext()
return user.isLoggedIn === true && user.user.userType === "Model" ? (
<div>
<Profile />
</div>
) : (
<div className="">
<h1>You are not authorized to view this page</h1>
{/* tw-mx-auto tw-mt-auto tw-font-extrabold tw-capitalize tw-text-3xl */}
</div>
)
}
export default profile;
Image of code 1 style
import React from "react";
import Profile from "../../components/model/Profile";
import { useAuthContext, useAuthUpdateContext } from "../../app/AuthContext"
function profile() {
const user = useAuthContext()
const { updateUser } = useAuthUpdateContext()
return user.isLoggedIn === true && user.user.userType === "Model" ? (
<div>
<Profile />
</div>
) : (
<div className="tw-mx-auto tw-mt-auto tw-font-extrabold tw-capitalize tw-text-3xl"> <-----// Difference is here from code 1
<h1>You are not authorized to view this page</h1>
{/* tw-mx-auto tw-mt-auto tw-font-extrabold tw-capitalize tw-text-3xl */}
</div>
)
}
export default profile;
Image of code 2 style
Components are working as expected but css style not.
If you are using CSS or SCSS modules, you will first have to import the style sheet in the component where you want to use the styles.
So in your example above, you would use something like:
import React from "react";
import Profile from "../../components/model/Profile";
import { useAuthContext, useAuthUpdateContext } from "../../app/AuthContext"
import styles from "../yourPath/../toStyles/stylesheet.module.css"
Don't forget to use "module.scss" if you are using SCSS in your project.
After that, you can treat the imported styles as object in JS code. So something like this in your code above:
<div className={styles.myClass}> <-----// Difference is here from code 1
<h1>You are not authorized to view this page</h1>
{/* tw-mx-auto tw-mt-auto tw-font-extrabold tw-capitalize tw-text-3xl */}
</div>
You can find more info in the official docs -> https://nextjs.org/docs/basic-features/built-in-css-support

Can't get MDX to work in a JavaScript Component. Just want Markdown to be turned to react components

Trying to make a react component with MDX that will turn markdown into react components. I want this so I can transform a blog article with embedded components (such as special article toolings and diagrams) from markdown stored in the DB into something presented on the page.
Been working on it for a few hours now and even my best attempts just result in literally nothing being displayed on the page. Where replacing the 'content' with a string displays.
I'm 100% baffled, lost and confused and really would appreciate help.
Original problem: https://www.reddit.com/r/reactjs/comments/mbdz7k/reactmarkdown_custom_component_declaration_how/
Working solution (but I am struggling to get it to work on my end). Provided by cmdq
https://codesandbox.io/s/dazzling-wescoff-ib8mv?file=/src/index.js
I've basically just moved the entire particular component file into being a JavaScript file but unfortunately I'm still running into many issues-- probably from lack of familiarality.
My current code is this in the file:
import ReactDOM from 'react-dom'
import renderToString from 'next-mdx-remote/render-to-string'
import hydrate from 'next-mdx-remote/hydrate'
import React, { Component } from 'react'
const exampleMdx = `
# h1
**foo**
<MyCustomComponent text="hell yeah" />
a
bar
`
const components = {
h1: (props) => <h1 style={{ color: 'tomato' }} {...props} />,
MyCustomComponent: ({ text }) => <marquee>{text}</marquee>,
}
const functionThing = async () => {
const mdxString = await renderToString(exampleMdx, {
components,
})
return hydrate(mdxString, { components });
}
export const ArticleTextTrial = () => {
let content = functionThing;
console.log(functionThing());
return (
<div className="articleMainTextSectionBody">{exampleMdx}
</div>
)
}

React Context API & Lifecycle methods - How to use together

I'm struggling to understand how to proceed with a small React app I am making.
I have a budget tracker, where you can add costs (mortgage, bills etc.) and they have a cost value. Each time you add, edit or delete one of these, I want the global state to change, which is stored in a context.
I basically have a 'remaining balance' value, that I want to recalculate each time something changes.
I figured I'd use a life cycle method or useEffect, but when I use that in my App.js (so that it watches for changes in all subcomponents), I can't get it to work, because the life cycle method is calling a method from my Context, but because it's not wrapped in the provider, it can't access the method in the Context.
Is this a common problem and is there are recommended way to fix it? I can't seem to find a similar problem on the GoOgLe.
App.js:
import React, { useState, useContext, useEffect } from "react";
import "./css/main.css";
import Header from "./layout/Header";
import BudgetInfo from "./components/BudgetInfo";
import PaymentForm from "./components/PaymentForm";
import CostToolbar from "./components/CostToolbar";
import Costs from "./components/Costs";
import BudgetContext from "./context/budgetContext";
import BudgetState from "./context/BudgetState";
const App = () => {
const budgetContext = useContext(BudgetContext);
const { updateBalance } = budgetContext;
useEffect(() => {
updateBalance();
});
return (
<BudgetState>
<Header darkModeToggle={toggleDarkMode} />
<main
className={"main-content" + (darkMode.darkMode ? " dm-active" : "")}
>
<div className="wrap content-wrap">
<BudgetInfo />
<PaymentForm />
<CostToolbar />
<Costs />
</div>
</main>
</BudgetState>
);
};
export default App;
You need to wrap the App component. Try the simple example.
import React, { useEffect, useContext } from 'react';
import ThemeContext from './../context/context';
const Sample = () => {
const context = useContext(ThemeContext);
useEffect(() => {
console.log(context,'--')
},[])
return(
<ThemeContext.Consumer>
{color => (
<p style={{ color }}>
Hello World
</p>
)}
</ThemeContext.Consumer>
)
}
export default Sample;

Can't manage to collect the data - React.js

First of, I'm a newbie at Javascript and React.js as you will probably observe. I'm currently trying to train myself.
I'm trying to display a "keyboard" (all letters from A to Z) and am trying to collect the data (the letter displayed) by implementing an onclick event on each letters.
However, even though my onclick event seems to be working, I'm getting an "undefined" answer in the console.
The handleLetterClicked() method is working fine but the handleKeyClicked() is not so I'm doing something wrong but can't get my head around it...
I hope you can help. thx in advance.
This is my keyboard component:
import React from 'react'
import './Keyboard.css'
const alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
const displayKeyboard = alphabet.map((lettreAlphabet) =>
<div className="keyboardKey">
{lettreAlphabet}
</div>
)
const Keyboard = ({ lettreAlphabet, onClick }) => (
<div className={lettreAlphabet} onClick={() => onClick(lettreAlphabet)}>
<span className="touche">
{displayKeyboard}
{lettreAlphabet}
</span>
</div>
)
export default Keyboard
This is my app:
import React, { Component } from 'react'
import GuessCount from './GuessCount'
import Letter from './Letter'
import Keyboard from './Keyboard'
import './App.css'
class App extends Component {
handleKeyClicked(lettreAlphabet){
console.log(lettreAlphabet, 'clicked')
}
handleLetterClicked(letter){
console.log(letter, 'alsoClicked')
}
render() {
return (
<div className="container">
<div className="pendu">
<GuessCount guesses={0} />
<Letter letter="Z" feedback="visible" onClick={this.handleLetterClicked} />
</div>
<div className="keyboard">
<Keyboard onClick={this.handleKeyClicked}/>
</div>
</div>
)
}
}
export default App;

Exporting default statement

I need to understand the export and import statement in React (Might involve the use of HOC)
So I have a higher component known as withclass.js like this
import React from 'react';
const withClass = (WrappedComponent, ClassName) => {
console.log(WrappedComponent)
console.log(ClassName)
return (props) => (
<div className={ClassName}>
<WrappedComponent />
</div>
)
}
export default withClass;
And inside our App.js, we do something like this
import withClass from '../hoc/withclass.js';
import classes from './App.css';
class App extends Component {
//some code here
//------ include render and return
export default withClass(App, classes.App);
Now, In Export statement I understand that he is passing two parameters which our withClass function requires as parameters but shouldn't he import something in withclass.js? How does our withclass.js receive those arguments?
Also, how does our return function (in withclass.js) get access to props here? (for example we passed props as an argument to our return function in withclass.js)?
I wasn't quite clear what you are asking for but regarding passing the argument you can do something like shown below. If I can get a little more explanation, I will update my answer.
import withClass from '../hoc/withclass.js';
class App extends Component {
//some code here
//------
return (
<Aux>
<button onClick={this.showPersonTrueHandler}>Show Persons </button>
<Ccockpit
coatiitle = {this.props.title}
cocPersonState = {this.state.showPerson}
cocperson = {this.state.person.length}
toggler = {this.togglerPersonHandler} />
{person}
</Aux>
)
}
}
export default withClass((parameter1, parameter2)=>{
//perform any action here...
})(App);

Categories