React - Save the work before leaving the page - reactjs

Using react, I'm trying to prevent the user from leaving a particular page displaying a message and saving his work.
I know that I could use Prompt to display a standard message with ok/cancel buttons, like this:
import { Prompt } from 'react-router'
<Prompt
when={hasToBlockNavigation}
message="Do you want to leave without saving?"
/>
but I'm looking for a way to display a custom component instead of the standard windows and to associate custom functions for the ok/cancel button. I found some other solution using the setRouteLeaveHook function, but it's not supported any more.
Any suggestions?
Thank you.

i believe you can use "react-router-navigation-prompt" which is according to their document :-
Promps user to confirm navigation. A replacement component for the react-router . Allows for more flexible dialogs.
npm i react-router-navigation-prompt
and then use your owm component like below - am using their example .
import NavigationPrompt from 'react-router-navigation-prompt';
import ConfirmNavigationModal from './your-own-code';
<NavigationPrompt when={this.state.shouldConfirmNavigation}>
{({onConfirm, onCancel}) => (
<ConfirmNavigationModal when={true} onCancel={onCancel} onConfirm={onConfirm}/>
)}
</NavigationPrompt>

Related

Creating preformatted text and code in React app

I am making a blog website in React in which user can submit code with other text. The entire code and other text will later be saved into the database. I am looking for the functionality like Stackoverflow's in which user can submit code and it is shown in the post in the original format.
I tried my best to search for the exact name of this functionality(My best guess is using LateX) but couldn't find any. So my exact question is what module or package do I need to represent the code submitted by the user in the original format as in Stackoverflow's question.
Please help me in the problem so I can get along with my work on my website.
After a bit of research into the topic of markdown, I found that react-markdown is a npm module that can be used to create markdown in text string. It is almost similar to the one used in Stackoverflow. But the recent version seems to have some bug, so I used an older version(5.0.0). If you also want to include syntax highlighting, you can use highlight.js. It can be very easily included with react-markdown. Below is an example of react-markdown:
import React from "react";
import ReactMarkdown from "react-markdown";
export default class App3 extends React.Component {
render(){
var value='
#Heading1
<b>line break</b>
_italics_';
return (
<div className="App">
<ReactMarkdown source={value} />
</div>
);}
}
u can also use
dangerouslySetInnerHTML
if u don't to install 3rd libary

React Bootstrap Nav.Link href/onSelect issues

I am using React Bootstrap NavLink to main navigation. What I'm trying to do is:
Allow opening in new tab with correct route (no checking if it should be left needed)
If user wants to change current tab page - check if it should be left (eg some changes on current page may not be saved)
My current version looks like this:
{paths && paths.map(path =>
<NavLink href={path} onSelect={this.handleOnSelect}>
{path}
</NavLink>
}
And works quite alright, but the problem starts when my url looks like domain.com/a/b. Let's assume I click on c, navLink creates route domain.com/a/c instead of domain.com/c. I tried using href={`/${path}`} and routing worked fine but it was ignoring onSelect.
Does anyone have an idea how this could be solved? Is that even possible to accomplish?

Can I live preview React components in VSCode?

New to React. I have been using live server for html files in VS Code but I can't seem to find the same functionality for React components (.js files). Maybe it's obvious or I'm looking for the wrong thing.
I'd like to make changes in the component, especially MUI styling and see the incremental results in a live preview, rather than the entire application having to refresh and click back to the form I'm working on. Any thoughts or suggestions? Thanks.
You don't have to change your code when using storybook. You just have to write new files, that import your component. Then you can pass it fake props to see how it behave depending in many scenarios. If you use create-react-app, it super easy to install, if you have your own config, then your level is good enough to follow their tutorial. The files are formatted like this: MyComponent.stories.js . Then storybook will look at all files that contains "stories" in their name, and launch them on port 6006 when you write yarn/npm run storybook in your terminal. I highly recommend storybook, it is used by most of companies.
Couldn't find a satisfactory solution and not willing to invest too much. Storybook looks like I'd have to change my code and because I'm still relatively new to react, not sure I'm up for that.
I'm just letting VSCode restart server each time I save a change then going to the browser and clicking through the menus to get to the page I'm working on.
For more complex ui changes, I'll create a code sandbox mini react app and just work on that for, like css changes, etc.
UPDATE:
I've implemented Storybook and I like it. After following the doc to install it I saw that I just needed to create a file (story) for a component like MyComponent.stories.js and put in the few lines of code to import and use it, passing in whatever props I wanted to see.
I decided to put my stories files into a separate separate stories folder under src. Here's an example for a Details component:
import React from 'react';
import { action } from '#storybook/addon-actions';
import Details from '../Details';
// How to display the component in Storybook page
export default {
title: 'Details',
component: Details,
// Our exports that end in "Data" are not stories.
excludeStories: /.*Data$/
};
// Props passed into component
export const recordData = {
record: {
id: '1',
createdOn: '2020-04-20 4:07 PM',
createdBy: 'dgarv',
modifiedOn: '2020-04-20 4:07 PM',
modifiedBy: 'dgarv',
}
};
// Use the actual component
export const Default = () => <Details {...recordData} />;
I've developed an extension named AutoPreview that you can use it to preview React/Vue component in VS Code.
You can get it in extension market: https://marketplace.visualstudio.com/items?itemName=jawei.autopreviewer&ssr=false#overview
You can use Preview.js to see the rendered code - https://previewjs.com/docs/platforms/vscode

How can I trigger a click on an element inside a child component (that I don't have access to)?

I have installed react-file-base64 into my React JS project and have implemented it like so:
import FileBase64 from 'react-file-base64';
import FileUpload from '../../forms/FileUpload'
...
class MyComponent extends Component {
render() {
return (
<FileUpload buttonText='Upload New Image'>
<FileBase64
multiple={ false }
onDone={ this.changeProfileImage }
/>
</FileUpload>
)
}
}
The code is obviously condensed for brevity.
As you can see, I've wrapped the FileBase64 component inside a custom FileUpload component - to do the old JS/CSS trick of hiding the file upload and triggering it via a different button press.
Given that I do not have direct access to edit the FileBase64 component, since it's been installed by NPM (and will possibly be updated by it in the future), and given that it is not a direct input element but rather a custom component that renders one - how can I trigger a click on the input element rendered by the FileBase64 component, from inside my FileUpload component?
You have a few options.
Reconsider using react-file-base64
This is a pretty minor NPM module, so ask yourself: is it worth using a few dozen lines of someone else's code instead of writing the functionality myself? Open source is amazing and leveraging other people's work can be a lifesaver, but learn to recognize when to lean on it and when not to.
Fork react-file-base64
Fork the original project and add whatever functionality you need to meet your requirements. Ideally do it in a well-written, well-documented way so that you can later open a pull request and contribute back to the project in a meaningful way.
Hack it a bit
It's good to stay inside of React as much as possible, but there are ways around it. You can, for example, still select DOM elements using plain old JavaScript. Remember that stuff? ;P
This would probably work fine - wrap the <FileBase64 /> component in a <div> that you can use to select any nested child <input> elements.
class MyComponent extends Component {
...
onBtnClick() {
this.inputWrapper.getElementsByTagName("input")[0].click();
}
render() {
return (
<FileUpload buttonText='Upload New Image' callback={this.onBtnClick} >
<div ref={(el) => this.inputWrapper = el} >
<FileBase64
multiple={ false }
onDone={ this.changeProfileImage }
/>
</div>
</FileUpload>
)
}
}
I dunno how exactly you're handling <FileUpload /> click callbacks but you get the idea. After a component renders, its DOM elements are laid bare for you to access. The trick is figuring out how to select those elements in the first place, and being careful that you don't break React in the process. But selecting an element and triggering a "click" event is pretty benign.
There are several triggers for this component that maybe suits your needs. Some of them are:
beforeUpload: Triggered before uploading. return true to continue or false to stop uploading.
doUpload: Triggered after the request is sent(xhr send | form submit).
onabort:riggered after you aborting a xhr.
uploadSuccess: Callback when upload succeed (according to the AJAX simply).
If you see the plugin documentation you can be how they work in detail, as well as more different events to interact with your input element inside your FileUpload component.

Reactjs overide markdown types with react-markdown

I am using contentful to get markdown to a react component that uses react-markdown to parse the markdown
import ReactMarkdown from 'react-markdown';
<Markdown source={text} />
Would I like to do is to override the Renderer so instead of it rendering ## as an h2 render i can pass a custom component to override the default h2 type to my own h2 component. How can i do that and is there and examples?
One of the options to <ReactMarkdown> is renderers.
One of the common renderers handles headings. If you look at the default rendering you'll see this:
heading: function Heading(props) {
return createElement('h' + props.level, getCoreProps(props), props.children);
},
So pass in your own heading handler. Check the level inside, roughly:
function CustomHeading(props) {
if (props.level !== 2) {
return createElement(`h${props.level}`, getCoreProps(props), props.children);
}
return <MyCustomElement {...props} />
}
If you don't have access to the code that commonmark-react-renderer gives you in the context of your function (which you probably won't) then you'd also need to duplicate what createElement gives you (but it's simple).
Unrelated: I've never used <ReactMarkdown> (but will), but this took me about five minutes of research. I'm including my path to encourage others to dig into their own questions and hopefully give some insight into how such things can be researched.
The react-markdown home page
Scanned through the "Options" section to see if custom rendering was trivially supported
Found the renderers option, which sounded promising
Clicked the link provided in that option's docs
Saw that heading was one of those (which made sense; I'd expect a renderer for every major formatting that Markdown supports)
Opened up the src directory to see if the implementation was easy to find
There was only one file, so I opened it
Searched the page for "heading" and found it
Cut and pasted that code here
The ability to read docs and follow trails is really important.

Resources