I have a Paragraph. in this para have lot of hashtags strings like #react ,#cool etc. I have to do that first filter all the hashtags strings from the paragraph and again place their original position with make it clickable.
Input
const str = "I am john mike . I love #reactProgramming. I have 2 years of experience in React Native Developer #ReactNative. #JS. I am working on the xyz Ltd. #xyz"
Output
I am john mike . I love #reactProgramming. I have 2 years of experience in React Native Developer #ReactNative. #JS. I am working on the xyz Ltd. #xyz
Now, all the hashtags is clickable and if we click on a specific hashtag. it should be log their own value like #JS.
Code:
import React,{useState,useEffect} from 'react'
export default function App() {
const str = "I am john mike . I love #reactProgramming. I have 2 years of experience in React Native Developer #ReactNative. #JS. I am working on the xyz Ltd. #xyz"
const [data,setData]=useState([]);
useEffect(() => {
});
const getHashTag = ()=>{
const regexp = /\B\#\w\w+\b/g
const result = str.match(regexp);
if (result) {
setData(result);
} else {
return false;
}
}
return (
<div className="App">
<h1>{str}</h1>
</div>
);
}
You can acheive your goal by using replace method, but instead of replacing on the original string, you can use replace method to generate your jSX elements and pushing them into an array and then render your array, like this:
const str = "I am john mike . I love #reactProgramming. I have 2 years of experience in React Native Developer #ReactNative. #JS. I am working on the xyz Ltd. #xyz";
function App() {
const handleClickOnTag = (tag)=>{ alert(tag) }
const renderTags = (str)=> {
let result = [];
let lastIndex = 0;
const regexp = /\B\#\w\w+\b/g
str.replace(regexp, (tag,tagIndex)=> {
result.push(str.slice(lastIndex, tagIndex));
lastIndex = tagIndex + tag.length;
result.push(<button key={tag} onClick={()=> handleClickOnTag(tag)}>{tag}</button>)
})
return result;
}
return (
<div className="App">
<h1>{renderTags(str)}</h1>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'))
button{
border: none;
background: #ddd;
padding: 8px;
cursor:pointer;
border-radius:3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>