Home > Back-end >  How to create and insert element in the middle of string in react?
How to create and insert element in the middle of string in react?

Time:02-06

As user types in input field, I want the matching letter in the text to be highlighted in red. So texts displayed is "Hello" and user types in "h" then I would like text to be updated to <span style="color:red">H</span>ello. I'm trying it with vanilla js way, which is createElement span then add style to it then append a letter, but no luck. What is the react way of accomplishing this? https://codesandbox.io/s/msft-machine-coding-react-ts-to9szx?file=/src/App.tsx:0-1613

App.tsx

import React, { useState, useEffect } from "react";
import "./styles.css";
import { posts } from "./data";

let slicedOne = posts.slice(0, 5);
let slicedTwo = posts.slice(5, 10);
let slicedThree = posts.slice(10);

export default function App() {
  const [feeds, setFeeds] = useState([]);
  const [currentView, setCurrentView] = useState(0);
  const [slicedFeeds, setSlicedFeeds] = useState([
    slicedOne,
    slicedTwo,
    slicedThree
  ]);
  const [texts, setTexts] = useState(
    slicedFeeds[currentView].map((feed) => feed.fullText)
  );

  let arr = [];
  const handleOnChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    let copiedTexts = texts;
    for (let text of copiedTexts) {
      for (let i = 0; i < text.length; i  ) {
        console.log(text[i]);
        if (text[i].toLowerCase() === e.target.value) {
          console.log("matched");
          let span = document.createElement("span"); // this is not working...
          span.style.color = "red";
          span.append(text[i]);
        }
      }
    }
  };

  return (
    <div>
      <div>
        <input type="text" onChange={handleOnChange} />
      </div>
      {slicedFeeds[currentView].map((feed, idx) => {
        return (
          <div key={feed.dateTimeCreated}>
            {feed.from.name} {feed.dateTimeLastModified}
            <div>{feed.fullText}</div>
            <br></br>
          </div>
        );
      })}
      <div>
        <button onClick={() => setCurrentView(0)}>1</button>
        <button onClick={() => setCurrentView(1)}>2</button>
        <button onClick={() => setCurrentView(2)}>3</button>
      </div>
    </div>
  );
}

data.tsx

export const posts = [
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Garima",
      email: "[email protected]"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hours.Hello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hoursHello this is just some random post created to show an example mock post for this coding challenge. this needs to be completed in two hours",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Reply",
    from: {
      name: "Viniket",
      email: "[email protected]"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Reply",
    from: {
      name: "Bhushan",
      email: "[email protected]"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Tanvi",
      email: "[email protected]"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Rahul",
      email: "[email protected]"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Deeksha",
      email: "[email protected]"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Swati",
      email: "[email protected]"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Ketki",
      email: "[email protected]"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Preksha",
      email: "[email protected]"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Sonali",
      email: "[email protected]"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Gagan",
      email: "[email protected]"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Pratiksha",
      email: "[email protected]"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Reply",
    from: {
      name: "Bhagyashree",
      email: "[email protected]"
    }
  },
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Milind",
      email: "[email protected]"
    }
  }
];

CodePudding user response:

The link that shanmukha vangaru suggested is a great place to start, but here is some working code to experiment with and study.

It uses the dangerouslySetInnerHTML prop but properly sanitises the input using DOMPurify, in order to be safe.

import { useState } from "react";
import DOMPurify from "dompurify";
const posts = [
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Garima",
      email: "[email protected]"
    }
  }
];

// Helper function to add highlighted markup to selected text
// based on the input keyword:
const highlighted = (keyword, text) =>
  // We sanitize the produced text to avoid XSS attacks
  // before passing the data to the dangerouslySetInnerHTML prop
  DOMPurify.sanitize(
    text.replace(
      new RegExp(`(${keyword})`, "gi"),
      "<span style='background:orange;'>$1</span>"
    )
);

export default function App() {
  const [keyword, setKeyword] = useState(null);
  // 1) Watch for input from the search box and update the state
  // The state change will trigger a re-render of the Component
  const handleOnChange = (e) => {
    setKeyword(e.target.value);
  };

  return (
    <>
      <input type="text" onChange={handleOnChange} />
      {posts.map((feed) => (
        <div key={feed.dateTimeCreated}>
          {feed.from.name} {feed.dateTimeLastModified}
          <p dangerouslySetInnerHTML={{ __html: highlighted(keyword, feed.fullText) }} />
        {/* The keyword is updated, there's a re-render and the feed text is filtered through the highlighter helper function to produce the highlighted markup */}
        </div>
      ))}
    </>
  );
}

Working demo:

const posts = [
  {
    fullText:
      "Hello this is just some random post created to show an example mock    post for this coding challenge",
    dateTimeCreated: "2020-07-20T18:44:11Z",
    dateTimeLastModified: "2020-07-20T18:44:11Z",
    type: "Post",
    from: {
      name: "Garima",
      email: "[email protected]"
    }
  }
];

  const highlighted = (keyword, text) =>
    DOMPurify.sanitize(
      text.replace(
        new RegExp(`(${keyword})`, "gi"),
        "<span style='background:orange;'>$1</span>"
      )
    );

function App() {
  const [keyword, setKeyword] = React.useState(null);
  const handleOnChange = (e) => {
    setKeyword(e.target.value);
  };
  return (
    <React.Fragment>
      <input type="text" onChange={handleOnChange} />
      {posts.map((feed) => (
        <div key={feed.dateTimeCreated}>
          {feed.from.name} {feed.dateTimeLastModified}
          <p dangerouslySetInnerHTML={{ __html: highlighted(keyword, feed.fullText) }} />
        </div>
      ))}
    </React.Fragment>
  );
}

ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.4.3/purify.min.js" crossorigin></script>
<div id="root"></div>

As always, there are many ways to solve a problem in software development, so make sure to study the other proposed solutions in the link provided in the comments. Each solution, has always pros and cons and must be balanced according to the requirements and trade offs.

CodePudding user response:

Can you check this solution

import React, { useState } from "react";

const App = () => {
  const [searchTerm, setSearchTerm] = useState("");
  const [text, setText] = useState("Lorem Ipsum is simply dummy text");

  const highlightText = (text, searchTerm) => {
    const regex = new RegExp(`(${searchTerm})`, "gi");
    const parts = text.split(regex);
    const highlighted = [];

    for (let i = 0; i < parts.length; i  ) {
      const part = parts[i];
      if (regex.test(part)) {
        highlighted.push(<mark key={i}>{part}</mark>);
      } else {
        highlighted.push(part);
      }
    }

    return highlighted;
  };

  return (
    <div>
      <input
        type="text"
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <p>{highlightText(text, searchTerm)}</p>
    </div>
  );
};

export default App;
  • Related