score:2
Accepted answer
sure thing, it's not really hard at all once you know the right tools.
here's a codesandbox example i whipped up, and a snippet of the same below (slightly adjusted for stack overflow's ancient babel version).
the idea is:
- use
string.split
's regexp mode to split the string into fragments that are either brackets or aren't - iterate over those fragments to keep track of the nesting level for the brackets (to properly colorize pairs)
- finally, return a react fragment with those children (this way we don't have to deal with array keys)
the colors in this example are only 3 levels deep, but you could easily add more, or make the colorization loop over n colors using the modulus operator.
function brackethighlighter({ text }) {
const children = react.usememo(() => {
const out = [];
let level = 0;
text.split(/([()])/).foreach((bit) => {
if (bit === "(") {
level++;
out.push(<span classname={"l" + level}>{bit}</span>);
} else if (bit === ")") {
out.push(<span classname={"l" + level}>{bit}</span>);
level--;
} else {
out.push(bit);
}
});
return out;
}, [text]);
return react.createelement(react.fragment, {}, ...children);
}
function app() {
const [text, settext] = react.usestate(
"(my text (is here and) i want (to highlight (something here)))"
);
return (
<div classname="app">
<input value={text} onchange={(e) => settext(e.target.value)} />
<br />
<brackethighlighter text={text} />
</div>
);
}
reactdom.render(<app />, document.getelementbyid("root"));
.l1 {
background-color: orange;
}
.l2 {
background-color: lightgreen;
}
.l3 {
background-color: cyan;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Source: stackoverflow.com
Related Query
- Javascript/react - highlight matching parenthesis
- React - highlight matching substring using array of characters and jsx tags
- Question mark before dot in javascript / react
- React 16: Warning: Expected server HTML to contain a matching <div> in <body>
- React 16: Warning: Expected server HTML to contain a matching <div> in <div> due to State
- What does React Native use to allow JavaScript to be executed on iOS and Android natively?
- react native downloading javascript bundle 100% stuck
- Writing embeddable Javascript plugin with React & Webpack
- Call external Javascript function from react components
- React Javascript displaying/decoding unicode characters
- Set React Input Field Value from JavaScript or JQuery
- Embeddable JavaScript widget with React
- Why can I omit the return statement with parenthesis in React
- Import third-party JavaScript library that normally self-executes into React app (using create-react-app)
- What's the difference between a JavaScript function and a React hook?
- Modify React Component's State using jQuery/Plain Javascript from Chrome Extension
- You need to enable javascript to run this app response when try to access local json file in react
- Can React Helmet inject a javascript object into <HEAD> tag?
- Using a regular javascript library inside a React component
- How does JavaScript mechanism behind react hooks work?
- How to use Emscripten compiled JavaScript within React / React Native
- For a React app, can the build process not create a JavaScript map file?
- Convert object to array in Javascript / React
- Dockerizing React in production mode: FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
- Javascript / React window.onerror fired twice
- Difference b/w React Typescript , React JavaScript and React Native?
- Best way to compress an image Javascript React Web App
- Force React to fire event through injected JavaScript
- High Jest Heap Memory Usage in JavaScript React Projects
- TypeError: this is undefined - React JS, Javascript
More Query from same tag
- Material UI TextField event for field leave
- Why the useEffect hook does not work with state variable in context?
- Custom Style to a form created using react-json schema form
- Why is onSubmit function not called during render even if we don't use an inline function to call it but onCLick functions are called during render?
- how to add class after random number is selected in reactjs
- How to make a post request using react redux?
- How to make a loop request with React using Axios?
- How to update data in the child component by click event in the parent component
- how to translate text files react (.md files)?
- React: I don't see thumbnails when using react-responsive-carousel
- chaining multiple async dispatch in Redux
- Button Click to display the API data on screen using array of objects
- using create-react-app and Sublimelinter ESlint together
- ReactJS - Is there a way to trigger a method by pressing the 'Enter' key inside <input/>?
- Routing with parameter issue in ReactJS
- React Hook useEffect has a missing dependency: 'refreshDisplay'. Either include it or remove the dependency array
- document.getElementById('pwMeter').style.display='none' not working as expected
- Get Value on ReactJS With REST API
- How to clear redux state once the user visit another route?
- Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object
- Navigate to a new page with React when I click on a button
- Fully react state management
- With redux form, how to combine values for initialValues?
- Can i use npm link to attach React components?
- Update property of React component in a separate component
- SCSS !default with css-modules
- Changing the value of object's property inside of a mapped array (buttons added through map function)
- Local Storage Keeps Resetting On Page Reload
- How would I go about uploading a image file using Socket-IO?
- Can I use window.localStorage in my React application?