New react state hook - useConverter
useConverter
React state hook that keeps track of the input and immediately generates the output based on the converter function.
Usage
import { useConverter } from 'react-use';
const Demo = () => {
const [input, setInput, output] = useConverter((data) => btoa(data), 'Hello World');
return (
<div>
<textarea value={input} onChange={(event) => setInput(event.target.value)} />
<pre>{output}</pre>
</div>
);
};
Checklist
- [x] Perform a code self-review;
- [x] Read the Contributing Guide;
- [x] Comment the code, particularly in hard-to-understand areas;
- [x] Add documentation;
- [x] Add hook's story at Storybook;
- [x] Cover changes with tests;
- [x] Ensure the test suite passes (
yarn test); - [x] Provide 100% tests coverage;
- [x] Make sure code lints (
yarn lint). Fix it withyarn lint:fixin case of failure; - [x] Make sure types are fine (
yarn lint:types);
Hello friends! I will be glad if you look at the hook I wrote :) I am ready to correct my mistakes and I want to make a contribution to this useful repository
i don't see the point of this hook tbh. Could you please elaborate a useful scenario in which this comes handy? Thanks"
i don't see the point of this hook tbh. Could you please elaborate a useful scenario in which this comes handy? Thanks
Initially, I developed this hook for our team's markdown editor. In it, the hook allows you to enter the markdown code in real time in one place of the editor and immediately see the result in the second place. An example of similar work can be seen here - https://dillinger.io
Code example (markdown editor):
import React, { useMemo } from 'react'
import Markdown from 'markdown-it'
import Highlight from 'highlight.js'
import Preview from '../components/Preview'
import Editor from '../components/Editor'
import useConverter from './useConverter' // our hook
export default () => {
const { render } = useMemo(() => {
return new Markdown({
highlight: (str, lang) => {
if (lang && Highlight.getLanguage(lang)) {
try {
return Highlight.highlight(lang, str).value
} catch (__) {}
}
return ''
},
})
}, [])
const [input, setInput, output] = useConverter((data) => render(data), '# Markdown Source Code')
return (
<div>
<Editor value={input} onChange={setInput}/>
<Preview value={output}/>
</div>
)
}
Also, our team in our projects often uses a similar hook to implement dynamic elements that allow you to enter data into input fields and immediately output the processed result based on the entered data. These elements are often components of searches, filters, sorts, etc.
Reading the docs, it's not clear what the second argument is for
Reading the docs, it's not clear what the second argument is for
Added jsdoc for hook args
Feedback pls