skip to Main Content

I’m using an array of objects for rendering cards:

someData = [
  {
   title: "some title",
   text: "some text where i need put link on word",
   linkedWord: "where"
 }
]

or it can be array of linkedWord.

Then I render my card with this data:

 {
   someData.map(item=> {
    <Card data={item} />
 }
)
}

The question is, how can I put link on word in Card component?

I’m trying to use split text before expected link and after, but it only works with 1 expected link.

I tried like this:

     const [strBefore, setStrBefor] = useState()
    const [strAfter, setStrAfter] = useState()
    const [LinkIndex, setLinkIndex] = useState()



    useEffect(() => {
        if (props.data.link) {
            let test = props.data.title.split(" ")
            test.map((item, index) => {
             if(item === props.data.link) {
                 setLinkIndex(index)
             }
            })
            if(LinkIndex === 0) {
                setStrAfter(test.splice(LinkIndex + 1, test.length).join(' '))
            }
            else if(LinkIndex === test.length) {
                setStrAfter('')
            }
            else {
                setStrBefor(test.splice(0, LinkIndex).join(' '))
                setStrAfter(test.splice(LinkIndex, test.length).join(' '))
            }
        }

    },[LinkIndex])

and render:

<h3>{strBefore} <a href='#'>{props.data.link}</a> {strAfter}</h3>

2

Answers


  1. Chosen as BEST ANSWER

    Solve this proble with marked-react

    npm i marked-react
    

    change key in object

    someData = [
         {
      text: 'some text [where](https://www.google.com) i need wrap word in link'
        }
       ]
    

    in component use Markdown component

    <Markdown>{props.data.text}</Markdown>
    

    and it wrap word on link


  2. You need to insert link in href:
    Instead to do this

    <h3>{strBefore}<a href='#'>{props.data.link}</a> {strAfter}</h3>
    

    You need to do

    <h3>{strBefore} <a href='{props.data.link}'>something</a> {strAfter}</h3>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search