score:2
you can deconstruct and extract the necessary values from your html string with regex and then use jsx instead of dangerouslysetinnerhtml. this component shows how to render your sample html string.
import react, { component } from 'react'
export default class app extends component {
render() {
const html = `<ul><li><strong>title1</strong><br/><a class="title1" href="/title1-link">title 1</a></li><li><strong>title2</strong><br/><a class="title2" href="/title2-link">title 2</a></li></ul>`
return (
<div>
<ul>
{html.match(/(<li>.*?<\/li>)/g).map( li => {
const title = li.match(/<strong>(.*?)<\/strong>/)[1]
const atag = li.match(/<a.*?\/a>/)[0]
const aclass = atag.match(/class="(.*?)"/)[1]
const href = atag.match(/href="(.*?)"/)[1]
const atext = atag.match(/>(.*?)</)[1]
return (
<li>
<strong>{title}</strong>
<br/>
<a classname={aclass} href={href}>{atext}</a>
</li>
)
})}
</ul>
</div>
)
}
}
from there you can simply wrap the a tag in your modallink component. i'm not sure this is exactly how you want to do that, but here is an example.
return (
<li>
<strong>{title}</strong>
<br/>
<modallink href={href}>
<a classname={aclass} href={href}>{atext}</a>
</modallink>
</li>
)
html.match(/(<li>.*?<\/li>)/g)
matches each <li>...</li>
within the html string in an array, which can then be mapped. then i extract the title, href, etc. out of each <li>...</li>
using captures (the part within parentheses), which can then be used in jsx. this answer provides more detail on the regular expressions used.
score:1
unfortunately i've never really used javascript which is why my answer will focus solely on the regex part of this question. (i've added an attempt a the bottom, though!)
if i understand it correctly you want to replace the <a href="somelink">sometitle</a>
tags with a <modallink href={'somelink'}>sometitle</modallink>
in a way that the somelink
and sometitle
will be in the modallink tag, too - please do correct me if i'm understanding this in a wrong way
now look at this regex pattern here
<a [^<]+?href\s*=\s*("|')(.*?)\1>(.*?)<\/a>
it will match with any tag starting with <a
and matches all characters until it finds an href
(with any number of whitespaces between the href and the equation mark). then it will search for a string between either ''
or ""
quotation marks and capture it in order to be used later on. it again matches until it finds the end of the tag >
and captures whatever is between that end and the closing tag <\a>
.
if you now use some method for replacing the matched regex in the given string (i'm sorry that i'm unfamiliar with how this would work in javascript) and replace it with this pattern
<modallink href={'$2'}> {$3} </modallink>
you will get a result like this for the example html string you're receiving:
<ul><li><strong>title1</strong> <br/> <modallink href={'title1-link'}> {title 1} </modallink></li><li><strong>title2</strong> <modallink href={'/title2-link'}> {title 2} </modallink>
the $2 and $3 part of the replacing pattern are placeholders for the before mentioned captured parts which will just be replaced with them as you can see. (they are capturing group 2 and 3 instead of starting with 1 simply because i've captured the quotation marks as capturing group 1 already)
you can try the pattern i've provided here.
while you can see and edit the regex and the string input on the upper part of the window, the replace pattern and its result can be found in the lower part.
edit: i've now tried my best with an online compiler to use javascript methods for replacing the tags with the tags and it seems to just work fine when using this method with the above mentioned regex:
var regexmatch = html.replace(/<a [^<>]+?href\s*=\s*("|')(.*?)\1[^<>]*?>(.*?)<\/a>/g, "<modallink href={'$2'}> {$3} </modallink>");
in this case the html
should of course be the html string in which you want to replace the <a>
tags.
you can also try this online here.
Source: stackoverflow.com
Related Query
- How to combine JSX component with dangerouslySetInnerHTML
- React / JSX Dynamic Component Name
- Component cannot be used as a JSX component. Its return type 'Element[]' is not a valid JSX element
- How to concatenate two JSX fragment or variables or string and component (in Reactjs)?
- Making an HTML string from a React component in background, how to use the string by dangerouslySetInnerHTML in another React component
- React: jsx in a variable vs a function vs a separate component
- React.js without JSX - "Warning: Something is calling a React component directly. Use a factory or JSX instead"
- How to avoid JSX component from condensing when React.js rendering it?
- Do I have to save react component files with a jsx extension
- Selectively rendering optional component properties in React JSX
- React: using React component inside of dangerouslySetInnerHTML
- React JSX vs function call to present component
- how to access vairables outside of map function in js and jsx in a React component
- Advantages of rendering a component vs a function returning JSX [React]
- Using JS React component in TypeScript: JSX element type 'MyComponent' is not a constructor function for JSX elements
- Next.js: 'Component' cannot be used as a JSX component
- Compile a JSX string to a component on the fly
- How to use <Link /> component inside dangerouslySetInnerHTML
- JSX vs component class instancing
- Call React Component Function from onclick in dangerouslySetInnerHTML
- Rendering a component in JSX vs via function
- Format number in jsx React component
- How to wait for in browser JSX compiler before call to render component
- JSX Component + dangerouslySetInnerHTML?
- How to load a react component written in JSX code from my Javascript code
- How can I import an existing React component defined in JSX in a Typescript module (.tsx)
- React component inside dangerouslySetInnerHTML
- Pasing objects as component property in React JSX
- TS2786 'Component' cannot be used as a JSX component
- Imported JSX component NewsСardMedium must be in PascalCase – isn't it?
More Query from same tag
- WordpressHEADLESS and Gatsby: base url wrong after executing gatsby build
- How to use JXS within html elements' attributes' double quotes as we use in PHP?
- Redux state is not getting initialized to initial state
- How to pass custom attributes onClick in React
- How to handle asynchronous calls from useEffect
- AsyncFunction Error using create react app
- How to export csv object in react
- How can I change a jQuery modal to a React modal?
- 'TypeError: zmq.zmqVersion is not a function' received when including ZeroMQ JS binding
- Should I dispatch an action for navigation in React/Redux
- How to pass key value pairs as parameters in Route Path?
- The best way to modify react state property with React Hooks
- react How to hide the Card when another location is pressed
- Formik: Need to render forms differently based on values in sibling forms
- Conditional rendering of multiple elements
- Why React says "Logout is not a function ?"
- How to trigger Material UI Select in Cypress
- Append react app directly to body in the right way
- Unable to get updated state after call multiple dispatch
- Warning: Each child in a list should have a unique "key" prop - I don't need to loop over this
- Es6 class with event handlers and issues with context/scope
- Property does not exist on type 'DetailedHTMLProps, HTMLDivElement>' with React 16
- How to filter all the fields in react?
- How can I set a different color for text and background of canvas HTML?
- React toDoApp removing a task functionality not working
- React ignoring Path causing wrong menu to show
- React-router subdomain routing
- React js redirect with authentication
- Deletion in FireStore (Latest Snip)
- React styled-components - How to render styles based on prop condition or pseudo class?