0

I'm building a type ahead feature in React.

I have wrapper component that has an array of objects, and it renders item; which's a stateless component.

So, suppose I have const name= 'Hasan'. Which gets parsed to >> const parsedName = Ha<span>san</span>; assuming the term to search for is san.

I have tried dangerouslySetInnerHTML={{ __html: parsedName }} attribute on the parent element, but it didn't work.

With plain html this would be: el.innerHTML = parsedName

The goal is to style the span as desired. Any ideas?

1 Answer 1

1

class Test extends React.Component {
  render() {
    const name = 'san';
    const parsedName = name.replace(new RegExp('san', 'ig'), '<span>span</span>');
    return (
    	<div dangerouslySetInnerHTML={{__html: parsedName}}/>
    );
  }
}

ReactDOM.render(
  <Test/>,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
</div>

Without code its hard to tell what's wrong. I have created a working snippet here that might help you debug your issue.

Updated the example based on the comment.

Sign up to request clarification or add additional context in comments.

2 Comments

That's correct and simple if I were to make it just a string. However, the problem arises when I populate the parsed name as a JSX element. (e.g. name = name.replace(new RegExp('san', 'ig'), <span className="matched">san</span>); Then it renders it as an object and can't parse it to html.
Hi Hasan. I have updated the example. Let me know if I have still misunderstood the problem..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.