React :: exchange part of a string for tag input

Asked

Viewed 82 times

0

I’ll describe what I have in my component: I get an API string with part of the content between * and I must exchange this part of the text for a <input />. You can have more than one piece of content per string.

Ex: Lorem ipsum *dolor sit amet* |  Lorem ipsum <input />;

I’m using this function to exchange what I get from the API for a specific string:

treatBlankQuestionsBlockStudent(text) {

    let blank = text.split('*');
    let finalBlank = [];

    blank.forEach((value, index) => {
      if (index % 2 === 0) {

        finalBlank.push(value);

      } else if (index % 2 !== 0) {

        let blank_parts = value.split(':');

        finalBlank.push('[insertInputHere]');
      }
    });

    return finalBlank;
  }

And in the rendering of the component I’m trying to make a replace of that string [insertInputHere] for <input />:

<label> 
 <span>{alternativeIndex + 1}) </span>
   {textAlternative.map((t,index) => 
     <span dangerouslySetInnerHTML={{ __html: t.replace("[insertInputHere]", 
        <input 
           className="custom-input" 
           type="text"
           id={alternativeId+alternativeIndex}
           data-id={index}
           onChange={(event) => this.handleChange(event.target.value)}
        />
      )}} className="question-alternative-text" /> )}
</label>

My problem is this: I’m unable to render the <input /> correctly, or returns [object Object] or does not render the onChange.

What is the best way to render?

1 answer

0


You need to pass a JSX array. Use the .split to remove pieces you don’t want and then add to that array the elements you need (for example with a reduce.

It would look like this (example):

const App = ({lorem}) => {
  const parts = lorem.split(/\*[^\*]+\*/g);
  const content = parts.reduce((arr, text, i, parts) => {
    if (i === parts.length - 1) return arr.concat(text);
    return arr.concat(text, <input type="text" />);
  }, []);
  
  return (<div>{content}</div>);
}

const lorem = 'Lorem *sfgffg* ipsum *dfggfd  sdgs  *.';
ReactDOM.render(
  <App lorem={lorem}/>, document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

  • 1

    I understood the logic you used. It worked perfectly. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.