How to make a textarea take markdown properties (HTML) - html

How do I use markdown properties in a HTML text area, a little like stack overflow's body area?
Of course I have my standard text area made out like this:
<textarea className="form__input form__group"
value={body}
onChange={e => setBody(e.target.value)} />
But I would like to be able to use markup/markdown tags in my text area to then get an output for when the post is made.
for example:
# Hello there,
> I want to be able to make mytext area be able to take this and then output markdown style body.
Hello there,
I want to be able to make mytext area be able to take this and then output markdown style body.

I would suggest using a library to assist with the markdown. I have used this one before and it works quite well: https://uiwjs.github.io/react-md-editor/
install: npm i #uiw/react-md-editor
Import into react: import MEditor from "#uiw/react-md-editor";
Then just use the MEditor and MEditor.markdown components to input and show your markdown.
There is way more info in the docs so just read https://uiwjs.github.io/react-md-editor/

I also use #uiw/react-md-editor as Croc suggested.
I would also recommend taking care of malicious scripts that untrusted bad actors/users may abuse.
Unfortunately, that's not well documented in the library documentation so here's how you may want to do it:
In edit mode:
<MDEditor
value={value}
autoFocus={false}
onChange={handleChange}
previewOptions={{ skipHtml: true, escapeHtml: true, transformLinkUri: null, linkTarget: '_blank' }}
/>
In preview/read-only mode:
<MDEditor.Markdown source={value} escapeHtml={true} skipHtml={true} transformLinkUri={null} />

Please try this code, To How to make a textarea take markdown properties (HTML).
<form>
<input name="title" type="text" placeholder="Title?" />
<textarea name="content" data-provide="markdown" rows="10"></textarea>
<label class="checkbox">
<input name="publish" type="checkbox"> Publish
</label>
<hr/>
<button type="submit" class="btn">Submit</button>
</form>
I hope this code will be useful to you.
Thank you.

I use react-markdown-editor-lite in most of my projects.
// import react, react-markdown-editor-lite, and a markdown parser you like
import * as React from 'react'
import * as ReactDOM from 'react-dom'
import MarkdownIt from 'markdown-it'
import MdEditor from 'react-markdown-editor-lite'
// import style manually
import 'react-markdown-editor-lite/lib/index.css';
// Register plugins if required
// MdEditor.use(YOUR_PLUGINS_HERE);
// Initialize a markdown parser
const mdParser = new MarkdownIt(/* Markdown-it options */);
// Finish!
function handleEditorChange({html, text}) {
console.log('handleEditorChange', html, text)
//You can use the text props to save it to your database
}
export default (props) => {
return (
<MdEditor
style={{ height: "500px" }}
renderHTML={(text) => mdParser.render(text)}
onChange={handleEditorChange}
/>
)
}

Related

how can I use useRef to treat the div as textarea

I have a long message saved as html format. I want to show this message to the screen without Html element as textarea input.
message = <p>Mobil &auml ........ </p>
Before I upgrade React version to V6 it was working fine as the code below.
I could scroll down and adjust the textarea box size to see the message inside the box.
<div
id="textarea"
name="message"
className="form-control"
dangerouslySetInnerHTML={{__html: this.state.message }}
ref="textarea"
/>
after updating to React V6, when I write exactly the same code, it gives me an error saying
"Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here".
My first approach was to just simply delete ref="textarea" but then the message is overflow from the box and cannot read other information below.
And my second approach is to use useRef() but im not really understanding how to incorporate it to my code.
any suggestion here plz.
First option:
import { useEffect, useRef } from 'react';
function Teste() {
const divElement = useRef<HTMLDivElement>(null);
useEffect(() => {
if (divElement.current) {
divElement.current.appendChild(document.createElement('textarea')).value = 'Hello World';
}
});
return <div ref={divElement} />;
}
export default Teste;
Second option:
https://www.radix-ui.com/docs/primitives/utilities/slot

How to instantiate a variable in Nuxt

I've tried a couple of different ways to instantiate a variable in Nuxt but neither way seems to work. I have read around the subject and suspect that perhaps what I'm trying to do is not compatible with Webpack but I'm not sure how.
Here is a jsFiddle of the code: jsfiddle.net/tutmoses/z2365g49/4
First in the script section I export dataSize:
<script>
export default {
data(){
return {
page_name: "Run Model",
dataSize: 1296
}
}
</script>
Then in the HTML above I'm trying to import it but nothing renders:
<div class="setting">
<span class="setting-label">Training Size:</span>
<input id="trainingSize" :value="dataSize"></input>
</div>
I've also tried this:
<div class="setting">
<span class="setting-label">Training Size:</span>
<input id="trainingSize" :value= {{ dataSize }}></input>
</div>
...but the value instantiates as
{{
I've tried both of the above options without binding the value but that didn't work either.
Another way I've tried is this in a separate file:
export const nnSettings = {
dataSize: 1296
}
And then importing it with this:
import nnSettings from '~/components/testindex.js'
Again, zip.
The reason why I'm importing the value is because other values will be calculated from it. What would be the standard, best way to do it?
Nuxt (Vue) uses v-model to bind to form input. Have a look here for more info on form bindings
<div class="setting">
<span class="setting-label">Training Size:</span>
<input id="trainingSize" v-model="dataSize"></input>
</div>

How to make Select Directory using React?

I need to upload all files from a folder to server.
I'm trying to implement Select Directory window, and not Select file.
The normal way like:
<input type="file" webkitdirectory directory/>
Did not work for me, and showed Select File window.
But when I created empty regular html file with this input tag, it was working fine.
Does anybody know how to implement the solution using React?
Thank you!
try bheptinh.
<input directory="" webkitdirectory="" type="file" />
In React 17 with Typescript, if you are using useRef Hook, the best bet is to extend React's HTMLAttributes (in the same file of your input) and then simply add directory and webkitdirectory attributes in input tag as
import * as React from "react";
export const ImportForm: React.FunctionComponent<FormProps> = (props) => {
const folderInput= React.useRef(null);
return (
<>
<div className="form-group row">
<div className="col-lg-6">
<label>Select Folder</label>
</div>
<div className="col-lg-6">
<input
type="file"
directory=""
webkitdirectory=""
className="form-control"
ref={folderInput}
/>
</div>
</div>
</>)
};
declare module 'react' {
interface HTMLAttributes<T> extends AriaAttributes, DOMAttributes<T> {
// extends React's HTMLAttributes
directory?: string; // remember to make these attributes optional....
webkitdirectory?: string;
}
}

reactjs dangerouslySetInnerHTML and dynamically adding classes to links

I'm new to reactjs and working on a project that is pushing json data to the template.
json structure
"description" : "Some text with a link and another link",
I propose using the following on the template
<p className='paragraph-margin-bottom-10 text--font-size-14 paragraph--justified' dangerouslySetInnerHTML={{ __html: lang.privacy[0].description }} />
but in terms of the output - I would maybe need to append a set of classes to ALL links. What is the best practice for this
so the links render with the following
<a class="text--font-size-14 hyperlink-primary" href="#">link</a>
I can imagine that many people will not agree with me. You can actually do this. But you shouldn't. It is bad enough that you want to use dangerouslySetInnerHTML. It is possible to parse html but there are many edge cases that you would need to handle.
Either tell your backend that they should return the links with proper classes or target the links inside the description directly with css.
See some similar question like: Using regular expressions to parse HTML: why not?
Using regular expressions to parse HTML: why not?
This is how I would do it. I will write the regex later if you run into some problems. I don't have much time to spare right now. Hope it will help. :)
import React from 'react';
import { render } from 'react-dom';
const htmlFromApi = 'some html from API'
const attachClassesToLinks = (htmlWithLinks) => {
// do something special
return htmlWithLinks
}
const App = () => (
<div>
<h1>My Component</h1>
<p dangerouslySetInnerHTML={{ __html: attachClassesToLinks(htmlFromApi) }} />
</div>
);
render(<App />, document.getElementById('root'));

Go - Getting the text of a single particular HTML element from a document with a known structure

In a little script I'm writing, I make a POST to a web service and receive an HTML document in response. This document is largely irrelevant to my needs, with the exception of the contents of a single textarea. This textarea is the only textarea in the page and it has a particular name that I know ahead of time. I want to grab that text without worrying about anything else in the document. Currently I'm using regex to get the correct line and then to delete the tags, but I feel like there's probably a better way.
Here's what the document looks like:
<html><body>
<form name="query" action="http://www.example.net/action.php" method="post">
<textarea type="text" name="nameiknow"/>The text I want</textarea>
<div id="button">
<input type="submit" value="Submit" />
</div>
</form>
</body></html>
And here's how I'm currently getting the text:
s := string(body)
// Gets the line I want
r, _ := regexp.Compile("<textarea.*name=(\"|')nameiknow(\"|').*textarea>")
s = r.FindString(s)
// Deletes the tags
r, _ = regexp.Compile("<[^>]*>")
s = r.ReplaceAllString(s, "")
I think using a full HTML parser might be a bit too much in this case, which is why I went in this direction, though for all I know there's something much better out there.
I appreciate any advice you may have.
Take a look at this package: https://github.com/PuerkitoBio/goquery. It's like jQuery but for Go. It allows you to do things like
text := doc.Find("strong").Text()
Full working example:
package main
import (
"bytes"
"fmt"
"github.com/PuerkitoBio/goquery"
)
var s = `<html><body>
<form name="query" action="http://www.example.net/action.php" method="post">
<textarea type="text" name="nameiknow">The text I want</textarea>
<div id="button">
<input type="submit" value="Submit" />
</div>
</form>
</body></html>`
func main() {
r := bytes.NewReader([]byte(s))
doc, _ := goquery.NewDocumentFromReader(r)
text := doc.Find("textarea").Text()
fmt.Println(text)
}
Prints: "The text I want".
Though this is not the best practice to parse HTML using regex. But as you wished, here it is:
(<textarea\b[^>]*\bname\s*=\s*(?:\"|')\s*nameiknow\s*(?:\"|')[^<]*<\/textarea>)