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
I have an .js file where I have my books as bellow:
export const booksData = [
{
id: "1",
title: "1491",
description: "A fantastic historical book",
genre: 'Historical',
image: "https://shop.radical-guide.com/wp-content/uploads/2020/06/1491-Front.jpg"
},
How can I import and display these books dynamically in my react application?
import { booksData } from "path/to/file.js"
You don't really need to pass it as a prop. Only if you are using a component, then yes, you should, eg:
<Component books={booksData} />
Then, in the Component function you pass it as a prop.
function Component(props){
return (
<>
{
props.books.map(book => {
return(
<h1>{book.title}</h1>
)})}
</>
)}
If not, you can directly import to the component that object(not recommended)
import { booksData } from "path/to/file.js"
And simply:
function Component(){
return (
<>
{
booksData.map(book => {
return(
<h1>{book.title}</h1>
)})}
</>
)}
// First of All You Need to import your .js file like that
import booksData from '/path/to/file.js'
everyone thanks for the help!
I have looked at several similar questions but have not been able to extrapolate their answers to solve my problem.
I am using a ReactJS application to consume JSON from a website. I'm using the code from https://pusher.com/tutorials/consume-restful-api-react and changing it to fit my situation.
Currently, when I view index.js, I get the error "TypeError:
assetList.assets is undefined." Given the the JSON and code below, what do I need to change to
display a list of the assets and their properties?
I would like something like the display to look like the Desired Display below.
Desired Display.
There are two 2 assets:<br/>
id: 1317 Filename: PROCESS_FLOW.pdf
id: 1836 Filename: 004527_FS.jpg
JSON consumed from website
{"totalNumberOfAssets":2,
"assets":[
{"id":"1317","attributes":{"Filename":["PROCESS_FLOW.pdf"]}},
{"id":"1836","attributes":{"Filename":["004527_FS.jpg"]}}
]}
components/assetList.js
import React from 'react'
const AssetList = ({assetList}) => {
return (
<div>
There are {assetList.totalNumberOfAssets} assets:
{assetList.assets.map((asset) => (
<div>
id: {asset.id} filename: {asset.filename}
</div>
))}
</div>
)
};
export default AssetList
App.js
import React, {Component} from 'react';
import AssetList from './components/assetList';
class App extends Component {
render() {
return (
<AssetList assetList={this.state.assetList} />
)
}
state = {
assetList: []
};
componentDidMount() {
fetch('http://ligitaddress/api/v1/asset')
.then(res => res.json())
.then((data) => {
this.setState({ assetList: data })
})
.catch(console.log)
}
}
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
On your first render, the value of this.state.assetList is an array:
state = {
assetList: []
};
However you are passing it into <AssetList>
const AssetList = ({assetList}) => {
return (
<div>
There are {assetList.totalNumberOfAssets} assets:
{assetList.assets.map((asset) => (
<div>
id: {asset.id} filename: {asset.filename}
</div>
))}
</div>
)
};
The line saying assetList.assets.map is trying to call map() on something that is undefined. (you can access the property assets on an array and it will be undefined) It seems like it expects assetList to be an object with an assets array in it, but in your parent component assetList is initialized to an array... in short you're confusing yourself as to what kind of data you expect to be where.
Either change your initial state to reflect how you expect it to be passed into <AssetList>:
state = {
assetList: {
assets: []
}
};
And/or change your <AssetList> component to properly check its prop:
const AssetList = ({assetList}) => {
return (
<div>
There are {assetList.totalNumberOfAssets} assets:
{Array.isArray(assetList.assets) && assetList.assets.map((asset) => (
<div>
id: {asset.id} filename: {asset.filename}
</div>
))}
</div>
)
};
This is happening because your components/assetList.js is trying to access assetList.assets on assetList.assets.map without it being defined.
When the API request is made and has not returned yet, the assets on assetList have not being defined, since assetList on App.js is initialized to an empty array.
You can replace the line on components/assetList.js with assetList.assets && assetList.assets.map(...) and that should do it
I would like to set the document title (in the browser title bar) for my React application. I have tried using react-document-title (seems out of date) and setting document.title in the constructor and componentDidMount() - none of these solutions work.
For React 16.8+ you can use the Effect Hook in function components:
import React, { useEffect } from 'react';
function Example() {
useEffect(() => {
document.title = 'My Page Title';
}, []);
}
To manage all valid head tags, including <title>, in declarative way, you can use React Helmet component:
import React from 'react';
import { Helmet } from 'react-helmet';
const TITLE = 'My Page Title';
class MyComponent extends React.PureComponent {
render () {
return (
<>
<Helmet>
<title>{ TITLE }</title>
</Helmet>
...
</>
)
}
}
import React from 'react'
import ReactDOM from 'react-dom'
class Doc extends React.Component{
componentDidMount(){
document.title = "dfsdfsdfsd"
}
render(){
return(
<b> test </b>
)
}
}
ReactDOM.render(
<Doc />,
document.getElementById('container')
);
This works for me.
Edit: If you're using webpack-dev-server set inline to true
For React 16.8, you can do this with a functional component using useEffect.
For Example:
useEffect(() => {
document.title = "new title"
}, []);
Having the second argument as an array calls useEffect only once, making it similar to componentDidMount.
As others have mentioned, you can use document.title = 'My new title' and React Helmet to update the page title. Both of these solutions will still render the initial 'React App' title before scripts are loaded.
If you are using create-react-app the initial document title is set in the <title> tag /public/index.html file.
You can edit this directly or use a placeholder which will be filled from environmental variables:
/.env:
REACT_APP_SITE_TITLE='My Title!'
SOME_OTHER_VARS=...
If for some reason I wanted a different title in my development environment -
/.env.development:
REACT_APP_SITE_TITLE='**DEVELOPMENT** My TITLE! **DEVELOPMENT**'
SOME_OTHER_VARS=...
/public/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
...
<title>%REACT_APP_SITE_TITLE%</title>
...
</head>
<body>
...
</body>
</html>
This approach also means that I can read the site title environmental variable from my application using the global process.env object, which is nice:
console.log(process.env.REACT_APP_SITE_TITLE_URL);
// My Title!
See: Adding Custom Environment Variables
Since React 16.8. you can build a custom hook to do so (similar to the solution of #Shortchange):
export function useTitle(title) {
useEffect(() => {
const prevTitle = document.title
document.title = title
return () => {
document.title = prevTitle
}
})
}
this can be used in any react component, e.g.:
const MyComponent = () => {
useTitle("New Title")
return (
<div>
...
</div>
)
}
It will update the title as soon as the component mounts and reverts it to the previous title when it unmounts.
import React from 'react';
function useTitle(title: string): void => {
React.useEffect(() => {
const prevTitle = document.title;
document.title = title;
return () => {
document.title = prevTitle;
};
}, []);
}
function MyComponent(): JSX.Element => {
useTitle('Title while MyComponent is mounted');
return <div>My Component</div>;
}
This is a pretty straight forward solution, useTitle sets the document title and when the component unmounts it's reset to whatever it was previously.
If you are wondering, you can set it directly inside the render function:
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
render() {
document.title = 'wow'
return <p>Hello</p>
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
)
For function component:
function App() {
document.title = 'wow'
return <p>Hello</p>
}
But, this is a bad practice because it will block the rendering (React prioritize the rendering first).
The good practice:
Class component:
class App extends React.Component {
// you can also use componentDidUpdate() if the title is not static
componentDidMount(){
document.title = "good"
}
render() {
return <p>Hello</p>
}
}
Function component:
function App() {
// for static title, pass an empty array as the second argument
// for dynamic title, put the dynamic values inside the array
// see: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
useEffect(() => {
document.title = 'good'
}, []);
return <p>Hello</p>
}
React Portals can let you render to elements outside the root React node (such at <title>), as if they were actual React nodes. So now you can set the title cleanly and without any additional dependencies:
Here's an example:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Title extends Component {
constructor(props) {
super(props);
this.titleEl = document.getElementsByTagName("title")[0];
}
render() {
let fullTitle;
if(this.props.pageTitle) {
fullTitle = this.props.pageTitle + " - " + this.props.siteTitle;
} else {
fullTitle = this.props.siteTitle;
}
return ReactDOM.createPortal(
fullTitle || "",
this.titleEl
);
}
}
Title.defaultProps = {
pageTitle: null,
siteTitle: "Your Site Name Here",
};
export default Title;
Just put the component in the page and set pageTitle:
<Title pageTitle="Dashboard" />
<Title pageTitle={item.name} />
you should set document title in the life cycle of 'componentWillMount':
componentWillMount() {
document.title = 'your title name'
},
update for hooks:
useEffect(() => {
document.title = 'current Page Title';
}, []);
Helmet is really a great way of doing it, but for apps that only need to change the title, this is what I use:
(modern way React solution - using Hooks)
Create change page title component
import React, { useEffect } from "react";
const ChangePageTitle = ({ pageTitle }) => {
useEffect(() => {
const prevTitle = document.title;
document.title = pageTitle;
return () => {
document.title = prevTitle;
};
});
return <></>;
};
export default ChangePageTitle;
Use the component
import ChangePageTitle from "../{yourLocation}/ChangePageTitle";
...
return (
<>
<ChangePageTitle pageTitle="theTitleYouWant" />
...
</>
);
...
You have multiple options for this problem I would highly recommend to either use React Helmet or create a hook using useEffect. Instead of writing your own hook, you could also use the one from react-use:
React Helmet
import React from 'react';
import { Helmet } from 'react-helmet';
const MyComponent => () => (
<Helmet>
<title>My Title</title>
</Helmet>
)
react-use
import React from 'react';
import { useTitle } from 'react-use';
const MyComponent = () => {
useTitle('My Title');
return null;
}
For React v18+, custom hooks will be the simplest approach.
Step 1: Create a hook. (hooks/useDocumentTitle.js)
import { useEffect } from "react";
export const useDocumentTitle = (title) => {
useEffect(() => {
document.title = `${title} - WebsiteName`;
}, [title]);
return null;
}
Step 2: Call the hook on every page with a custom title according to that page. (pages/HomePage.js)
import { useDocumentTitle } from "../hooks/useDocumentTitle";
const HomePage = () => {
useDocumentTitle("Website Title For Home Page");
return (
<>
<main>
<section>Example Text</section>
</main>
</>
);
}
export { HomePage };
Works well for dynamic pages as well, just pass the product title or whatever content you want to display.
Simply you can create a function in a js file and export it for usages in components
like below:
export default function setTitle(title) {
if (typeof title !== "string") {
throw new Error("Title should be an string");
}
document.title = title;
}
and use it in any component like this:
import React, { Component } from 'react';
import setTitle from './setTitle.js' // no need to js extension at the end
class App extends Component {
componentDidMount() {
setTitle("i am a new title");
}
render() {
return (
<div>
see the title
</div>
);
}
}
export default App
You can use the following below with document.title = 'Home Page'
import React from 'react'
import { Component } from 'react-dom'
class App extends Component{
componentDidMount(){
document.title = "Home Page"
}
render(){
return(
<p> Title is now equal to Home Page </p>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
or You can use this npm package npm i react-document-title
import React from 'react'
import { Component } from 'react-dom'
import DocumentTitle from 'react-document-title';
class App extends Component{
render(){
return(
<DocumentTitle title='Home'>
<h1>Home, sweet home.</h1>
</DocumentTitle>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
Happy Coding!!!
I haven't tested this too thoroughly, but this seems to work. Written in TypeScript.
interface Props {
children: string|number|Array<string|number>,
}
export default class DocumentTitle extends React.Component<Props> {
private oldTitle: string = document.title;
componentWillUnmount(): void {
document.title = this.oldTitle;
}
render() {
document.title = Array.isArray(this.props.children) ? this.props.children.join('') : this.props.children;
return null;
}
}
Usage:
export default class App extends React.Component<Props, State> {
render() {
return <>
<DocumentTitle>{this.state.files.length} Gallery</DocumentTitle>
<Container>
Lorem ipsum
</Container>
</>
}
}
Not sure why others are keen on putting their entire app inside their <Title> component, that seems weird to me.
By updating the document.title inside render() it'll refresh/stay up to date if you want a dynamic title. It should revert the title when unmounted too. Portals are cute, but seem unnecessary; we don't really need to manipulate any DOM nodes here.
You can use ReactDOM and altering <title> tag
ReactDOM.render(
"New Title",
document.getElementsByTagName("title")[0]
);
the easiest way is to use react-document-configuration
npm install react-document-configuration --save
Example:
import React from "react";
import Head from "react-document-configuration";
export default function Application() {
return (
<div>
<Head title="HOME" icon="link_of_icon" />
<div>
<h4>Hello Developers!</h4>
</div>
</div>
);
};```
you can create TabTittleHelper.js and
export const TabTittle = (newTitle) => {
document.title=newTitle;
return document.title;
};
later you writed all screens
TabTittle('tittleName');
I am not sure if it is a good practice or not, but In index.js headers I put:
document.title="Page Title";
const [name, setName] = useState("Jan");
useEffect(() =>
{document.title = "Celebrate " + {name}.name ;}
);
I wanted to use page title to my FAQ page. So I used react-helmet for this.
First i installed react-helmet using npm i react-helmet
Then i added tag inside my return like this:
import React from 'react'
import { Helmet } from 'react-helmet'
const PAGE_TITLE = 'FAQ page'
export default class FAQ extends Component {
render () {
return (
{ PAGE_TITLE }
This is my faq page
)
}
}
If you're a beginner you can just save yourself from all that by going to the public folder of your react project folder and edit the title in "index.html" and put yours. Don't forget to save so it will reflect.
I'm having a problem with my React component. The nested children of my component ControlPanel don't seem to be rendering. Here is my code:
class App extends Component {
render() {
return (
<div className="App">
<ControlPanel>
<CustomerDisplay />
</ControlPanel>
</div>
);
}
}
I have the following two lines at the top of this file:
import ControlPanel from './components/control_panel';
import CustomerDisplay from './components/customer_display';
And here is my ControlPanel Component:
import React from 'react';
import CSSModules from 'react-css-modules';
import styles from './styles.scss';
const ControlPanel = () => {
return (
<div className="control_panel" id="control_panel">
</div>
);
}
export default CSSModules(ControlPanel, styles);
I have tried:
Calling the component as a full HTML tag (opening & closing)
Nesting the CustomerDisplay component in the ControlPanel component (in the ControlPanel's index.jsx file)
I know that nesting component's is possible. I've seen it done. For some reason it just won't work for me.
To allow components to contain children and render them correctly, you have to use this.props.children. This is passed to all components with children as a prop and contains the children of the component, as explained by the React documentation:
Containment
Some components don't know their children ahead of time. This is especially common for components like Sidebar or Dialog that represent generic "boxes".
We recommend that such components use the special children prop to pass children elements directly into their output:
function FancyBorder(props) {
return (
<div className={'FancyBorder FancyBorder-' + props.color}>
{props.children}
</div>
);
}
This lets other components pass arbitrary children to them by nesting the JSX
function WelcomeDialog() {
return (
<FancyBorder color="blue">
<h1 className="Dialog-title">
Welcome
</h1>
<p className="Dialog-message">
Thank you for visiting our spacecraft!
</p>
</FancyBorder>
);
}
As described in the documentation, some components don't know their children ahead of time -- they may be generic wrappers or boxes of content that vary, which is what your ControlPanel is. So, to render the children of your component, you must render the children from the children prop explicitly in the parent's render method. Thus, apply it like this to your code:
const ControlPanel = (props) => {
return (
<div className="control_panel" id="control_panel">
{props.children}
</div>
);
}
Notice how props.children is rendered (not this.props.children because it is a function component).
You can access the nested elements through props. So in your case do this:
const ControlPanel = (props) => {
return (
<div className="control_panel" id="control_panel">
{props.children}
</div>
);
}
You need to render the children in ControlPanel
const ControlPanel = ({ children }) => {
return (
<div className="control_panel" id="control_panel">
{children}
</div>
);
}
function FancyBorder(props) {
return (
<div className={'FancyBorder FancyBorder-' + props.color}>
{props.children}
</div>
);
}
export default function WelcomeDialog() {
return (
<FancyBorder color="blue">
<h1 className="Dialog-title">
Welcome
</h1>
<p className="Dialog-message">
Thank you for visiting our spacecraft!
</p>
</FancyBorder>
);
}
Anything inside the<FancyBorder>JSX tag gets passed into the FancyBorder component as childrenprop. Since FancyBorder renders {props.children} inside a <div>, the passed elements appear in the final output.
This is what I was looking after, check it out here
https://reactjs.org/docs/composition-vs-inheritance.html
Your App.js (I understand that it is your JSX Index) should be:
import React from 'react';
import ReactDOM from 'react-dom';
export default class App extends Component {
render() {
return (
<div className="App">
<ControlPanel>
<CustomerDisplay />
</ControlPanel>
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('YOUR_ROOT_ID'));
Try to add export default before class (in all your components).