What is the most effective method for incorporating personalized React components in the midst of strings or paragraph tags

Summary: Exploring the frontend world for the first time. Attempting to integrate custom components within p-tags for a website, but facing challenges in making them dynamically changeable based on user interaction.

Greetings all! As a newbie in front-end development, I come seeking assistance with my introductory query, overlooking any inaccuracies in terminology or question structure!

My current project involves working with React, where I've crafted custom components to embed on my webpage within p-tags.

For instance, when I create a custom component like and insert it as follows:

function test{
return(
<p>Hello! This is a <ShowDefinition word="website"/> built using React! </p>
)}

However, I aspire to have multiple contents that dynamically update through an incremental index. Therefore, I store my content in a separate jsx file as a dictionary.

Upon attempting something similar to this:

function test{
    return(
    <div>{script[index].content}</div>
    )};

where 
script[index].content = '<p>Hello! This is a <ShowDefinition word="website"/> built using React! </p>';

The outcome displayed merely as a string literal on the page. I experimented by enclosing my string in {}, but to no avail.

I also tried implementing dangerouslySetInnerHTML along with DOMPurify to sanitize the HTML code:

dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(script[index].content)}};

This approach worked; however, it omitted all my custom components, rendering the example sentence as "Hello! This is a built using React!"

Realizing that dangerouslySetInnerHTML cannot parse custom components and solely accepts HTML, I'm now uncertain about the next course of action.

One idea I considered was storing the content in an MD file and parsing it, but my limited understanding of MD files/MD parsers leaves me skeptical of its effectiveness in resolving my issue.

Your valuable guidance would be immensely appreciated.

Thank you sincerely.

Answer №1

When working with React, it's important to approach things differently. While it may be possible to manipulate elements using React.createElement or dangerouslySetInnerHTML,, I recommend taking a look at this guide first to understand the React way of thinking.

If I were to implement this in React, I would consider using custom hooks or conditional logic to handle rendering JSX dynamically.

Check out the demo on CodeSandbox

import "./styles.css";
import React from "react";

const useContentFromIndex = (index) => {
  return () => {
    if (index === 0) return <p> Index 0 </p>;
    if (index === 1) return <p> Index 1 </p>;
    return <p> Index 2 </p>;
  };
};

export default function App({ index = 0 }) {
  const CustomContent = useContentFromIndex(index);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <CustomContent />
    </div>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

HTML5 Video validation is not working properly

In my current project, I initially used embedded Youtube videos but faced issues with validation. Decided to explore HTML5 video elements as an alternative, but encountered some challenges. While attempting to validate the code, strange errors popped up: ...

Error: guild is not defined | discord.js

Having trouble with a ReferenceError that says guild is not defined? I recently encountered a similar issue with members but managed to fix it by adding a constant. As someone new to javascript and node.js, I could use some assistance. I've even tried ...

Show Struts2 error message on an HTML webpage

I have included error and message handling in my Struts2 action class using the addActionMessage and addActionError methods. I am now looking for code that will allow me to display these messages and errors on the HTML page. Is it feasible to do so? ...

The frequency of database updates exceeds expectations - involving vue.js this.$router.push and express operations

Having some trouble updating a MongoDB with this code. It seems to be updating three times instead of just once due to having three dates in the posts.date field. Utilizing Vue, Mongo, and Express for this project, I have the following data structure: { ...

Utilize useState and useEffect to efficiently sort through an item list based on its current state

I am currently working on an application where I have a list of items and I need to create a details page for each item when clicked. I am facing some challenges in implementing this functionality using useState, useEffect, and typescript. I have previousl ...

When implementing 'useGlobalGuards' in NestJS, remember to exclude endpoints for enhanced security

After implementing the useGlobalGuards method in my main.ts file, all endpoints now utilize the AuthGuard. This guard triggers a 401 error if a valid auth token is not present in the request header. Previously, I used @UseGuards(AuthGuard) on individual cl ...

Unable to eliminate user registration feature with Meteor and React

Exploring the world of Meteor and diving deep into its functionalities, I am currently focused on creating a user login and signup page with personalized control panels for each registered user. Although I have successfully implemented the signup and logi ...

Guide on transferring JavaScript Objects from the Front End to Spring Boot Back-end and effectively processing and parsing them

After struggling with this issue repeatedly while developing my web apps, I've reached a breaking point and need some help. My frustration might come across as venting, but I'm genuinely stuck. The challenge I'm facing is sending key-value ...

The React Bootstrap modal refuses to fully close no matter how many times I click away or even on the close button

I am facing an issue with a modal in my React component. When I open the modal, it does not completely close when I try to click away or hit the close button. The backdrop disappears but the modal itself remains on the screen. (Screenshots attached for r ...

Ways to prevent modal from flickering during event changes

I'm struggling with a current issue and need help identifying the cause and finding a solution. The problem arises from having a nested array of Questions, where I display a Modal onClick to show Sub questions. However, when clicking on the Sub Quest ...

Utilizing camera perspective for coordinate system in Three.js

This question may seem basic, but I'm having trouble grasping it. I'm working on a scene using Three.js and the camera setup is as follows: var camera = new THREE.PerspectiveCamera( 85, window.innerWidth/window.innerHeight, 0.1, 1000 ); camera. ...

HTML displaying inaccurately

While following a Ruby tutorial to create a Sample App, I encountered an issue with the signup page. The errors displayed during sign up are not formatted correctly - the period at the end of the error line appears before it, and both the asterisk and bull ...

Why is it necessary to define a property outside the constructor in Typescript, when in Javascript I wouldn't have to do that?

When working with Javascript, creating a class like the one below allows us to avoid declaring and initializing a property named logs outside of the constructor: class Logger { constructor() { this.logs = []; } } However, transitioning to TypeScri ...

The issue I am encountering is that the value from jQuery autocomplete is not getting transferred to the

I'm having trouble retrieving a textInput from a Form where I am extracting values from Jquery Autocomplete. The selected value is not being transferred to the form. Can you please help me identify what I am missing? $(function() { var availableT ...

Using a Next.js custom server results in Material-UI being rendered as static content

Currently in the process of developing a NodeJS application using Koa, React, Material-UI, and NextJS. I've come across examples of integrating a server rendering framework with Material-UI. However, these examples assume the use of NextJS' defa ...

What is the correct method for retrieving a specific child element in React?

In my React project, I have created a component that consists of various subcomponents: import React, { FunctionComponent } from 'react'; import { FormControl, FormGroup, FormGroupProps, FormLabel, FormText, FormTextProps } from 'react-boots ...

Tips for duplicating specific div elements

Is there a way to create copies of selected divs within the same panel using a Javascript report designer? I attempted to achieve this by using the following code snippet: function DesignerClone() { $(".ui-selected").each(function () { va ...

When the font size is set below 16px on an iPhone, iOS will automatically zoom in to compensate

Currently, I am running tests on my app using an iPhone. Everything seems to be working correctly on the iPad, but when I try clicking on a text field on the iPhone, the view automatically zooms in. It appears that setting the font size to 16px or larger r ...

Issue with NPM's manual review process following recent package updates

Upon downloading node-sass, I encountered the following warning message: "found 9 vulnerabilities (4 moderate, 5 high) in 1869 scanned packages. 9 vulnerabilities require manual review. See the full report for details." Despite attempting to manually insta ...

The collapsing z-index menu in Bootstrap 4 is experiencing CSS issues and is not functioning correctly

I have a bootstrap 4 menu with a slide effect that is functioning correctly, but there seems to be an issue with the z-index value I have set for it. Specifically, there is some content within a parallax jumbotron that is overlapping the menu links. I need ...