insert html with react variable statements (jsx) [duplicate]

  • Last Update :
  • Techknowledgy :

and have it insert the HTML as expected? I haven't seen or heard anything about a react function that could do this inline, or a method of parsing things that would allow this to work. By using '' the sets the value to a string and React has no way of knowing that it is a HTML element. You can do the following to let React know it is a HTML element - 2 This does not answer the question. The content of thisIsMyCopy is itself JSX, not a string of HTML. So you're literally pasting JSX into JSX. – Antares42 Apr 10, 2019 at 20:12

You can use dangerouslySetInnerHTML, e.g.

render: function() {
    return (
        <div className="content" dangerouslySetInnerHTML={{__html: thisIsMyCopy}}></div>
    );
}

It is probably a good idea to sanitize the HTML string via a utility such as DOMPurify if you are not 100% sure the HTML you are rendering is XSS (cross-site scripting) safe.

Example:

import DOMPurify from 'dompurify'

const thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';


render: function() {
    return (
        <div className="content" dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(thisIsMyCopy)}}></div>
    );
}

Suggestion : 2

Insert HTML with React Variable Statements (JSX) and have it insert the HTML as expected? I haven't seen or heard anything about a react function that could do this inline, or a method of parsing things that would allow this to work. and to insert it into react like so, and have it work? Write a mode method in Java to find the most frequently occurring element in an array

I am building something with React where I need to insert HTML with React Variables in JSX. Is there a way to have a variable like so:

var thisIsMyCopy = '<p>copy copy copy <strong>strong copy</strong></p>';
2._
render: function() {
    return (
        <div className="content">{thisIsMyCopy}</div>
    );
}

You can use dangerouslySetInnerHTML, e.g.

render: function() {
    return (
        <div className="content" dangerouslySetInnerHTML={{__html: thisIsMyCopy}}></div>
    );
}

Suggestion : 3

Try Fragment, if you don't want any of above. Using React Bootstrap + Next.JS, How do i go about getting the content of a textbox within a React Component and sending it back to my Index.js You don't need any special library or "dangerous" attribute. You can just use React Refs to manipulate the DOM: Insert custom React component into a String variable with html content

You can use dangerouslySetInnerHTML, e.g.

render: function() {
    return (
        <div className="content" dangerouslySetInnerHTML={{__html: thisIsMyCopy}}></div>
    );
}

You can also include this HTML in ReactDOM like this:

var thisIsMyCopy = (<p>copy copy copy <strong>strong copy</strong></p>);

ReactDOM.render(<div className="content">{thisIsMyCopy}</div>, document.getElementById('app'));

If anyone else still lands here. With ES6 you can create your html variable like so:

render(){
    var thisIsMyCopy = (
        <p>copy copy copy <strong>strong copy</strong></p>
    );
    return(
        <div>
            {thisIsMyCopy}
        </div>
    )
}

If you using hook want to set it in a state somewhere with any condition

const [thisIsMyCopy, setThisIsMyCopy] = useState(<Fragment>
   <p>copy copy copy <strong>strong copy</strong></p>
</Fragment>);

To avoid linter errors, I use it like this:

  render() {
    const props = {
      dangerouslySetInnerHTML: { __html: '<br/>' },
    };
    return (
        <div {...props}></div>
    );
  }

Suggestion : 4

In the example below, we declare a variable called name and then use it inside JSX by wrapping it in curly braces: In the example below, we embed the result of calling a JavaScript function, formatName(user), into an <h1> element. You can put any valid JavaScript expression inside the curly braces in JSX. For example, 2 + 2, user.firstName, or formatName(user) are all valid JavaScript expressions. JSX produces React “elements”. We will explore rendering them to the DOM in the next section. Below, you can find the basics of JSX necessary to get you started.

1._
const element = <h1>Hello, world!</h1>;
2._
const name = 'Josh Perez';const element = <h1>Hello, {name}</h1>;
3._
function formatName(user) {
  return user.firstName + ' ' + user.lastName;
}

const user = {
  firstName: 'Harper',
  lastName: 'Perez'
};

const element = (
  <h1>
    Hello, {formatName(user)}!  </h1>
);
5._
const element = <a href="https://www.reactjs.org"> link </a>;
6._
const element = <img src={user.avatarUrl}></img>;

Suggestion : 5

Note that a HOC doesn’t modify the input component, nor does it use inheritance to copy its behavior. Rather, a HOC composes the original component by wrapping it in a container component. A HOC is a pure function with zero side-effects. On mount, add a change listener to DataSource. The problem here isn’t just about performance — remounting a component causes the state of that component and all of its children to be lost. Resist the temptation to modify a component’s prototype (or otherwise mutate it) inside a HOC.

1._
const EnhancedComponent = higherOrderComponent(WrappedComponent);
2._
class CommentList extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {
      // "DataSource" is some global data source
      comments: DataSource.getComments()
    };
  }

  componentDidMount() {
    // Subscribe to changes
    DataSource.addChangeListener(this.handleChange);
  }

  componentWillUnmount() {
    // Clean up listener
    DataSource.removeChangeListener(this.handleChange);
  }

  handleChange() {
    // Update component state whenever the data source changes
    this.setState({
      comments: DataSource.getComments()
    });
  }

  render() {
    return (
      <div>
        {this.state.comments.map((comment) => (
          <Comment comment={comment} key={comment.id} />
        ))}
      </div>
    );
  }
}
3._
class BlogPost extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {
      blogPost: DataSource.getBlogPost(props.id)
    };
  }

  componentDidMount() {
    DataSource.addChangeListener(this.handleChange);
  }

  componentWillUnmount() {
    DataSource.removeChangeListener(this.handleChange);
  }

  handleChange() {
    this.setState({
      blogPost: DataSource.getBlogPost(this.props.id)
    });
  }

  render() {
    return <TextBlock text={this.state.blogPost} />;
  }
}
5._
// This function takes a component...
function withSubscription(WrappedComponent, selectData) {
  // ...and returns another component...
  return class extends React.Component {
    constructor(props) {
      super(props);
      this.handleChange = this.handleChange.bind(this);
      this.state = {
        data: selectData(DataSource, props)
      };
    }

    componentDidMount() {
      // ... that takes care of the subscription...
      DataSource.addChangeListener(this.handleChange);
    }

    componentWillUnmount() {
      DataSource.removeChangeListener(this.handleChange);
    }

    handleChange() {
      this.setState({
        data: selectData(DataSource, this.props)
      });
    }

    render() {
      // ... and renders the wrapped component with the fresh data!
      // Notice that we pass through any additional props
      return <WrappedComponent data={this.state.data} {...this.props} />;
    }
  };
}
6._
function logProps(InputComponent) {
   InputComponent.prototype.componentDidUpdate = function(prevProps) {
      console.log('Current props: ', this.props);
      console.log('Previous props: ', prevProps);
   };
   // The fact that we're returning the original input is a hint that it has
   // been mutated.
   return InputComponent;
}

// EnhancedComponent will log whenever props are received
const EnhancedComponent = logProps(InputComponent);

Suggestion : 6

This new function useState is the first “Hook” we’ll learn about, but this example is just a teaser. Don’t worry if it doesn’t make sense yet! You can start learning Hooks on the next page. On this page, we’ll continue by explaining why we’re adding Hooks to React and how they can help you write great applications. There are no plans to remove classes from React. You can read more about the gradual adoption strategy for Hooks in the bottom section of this page.

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Suggestion : 7

Now let’s say that our chat application also has a contact list, and we want to render names of online users with a green color. We could copy and paste similar logic above into our FriendListItem component but it wouldn’t be ideal: Do two components using the same Hook share state? No. Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated. In the beginning, our stated goal was to remove the duplicated logic from the FriendStatus and FriendListItem components. Both of them want to know whether a friend is online.

1._
import React, {
   useState,
   useEffect
} from 'react';

function FriendStatus(props) {
   const [isOnline, setIsOnline] = useState(null);
   useEffect(() => {
      function handleStatusChange(status) {
         setIsOnline(status.isOnline);
      }
      ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
      return () => {
         ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
      };
   });
   if (isOnline === null) {
      return 'Loading...';
   }
   return isOnline ? 'Online' : 'Offline';
}
2._
import React, { useState, useEffect } from 'react';

function FriendListItem(props) {
  const [isOnline, setIsOnline] = useState(null);  useEffect(() => {    function handleStatusChange(status) {      setIsOnline(status.isOnline);    }    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);    return () => {      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);    };  });
  return (
    <li style={{ color: isOnline ? 'green' : 'black' }}>
      {props.friend.name}
    </li>
  );
}
3._
import {
   useState,
   useEffect
} from 'react';

function useFriendStatus(friendID) {
   const [isOnline, setIsOnline] = useState(null);

   useEffect(() => {
      function handleStatusChange(status) {
         setIsOnline(status.isOnline);
      }

      ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
      return () => {
         ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
      };
   });

   return isOnline;
}
5._
function FriendStatus(props) {
   const isOnline = useFriendStatus(props.friend.id);
   if (isOnline === null) {
      return 'Loading...';
   }
   return isOnline ? 'Online' : 'Offline';
}
6._
function FriendListItem(props) {
  const isOnline = useFriendStatus(props.friend.id);
  return (
    <li style={{ color: isOnline ? 'green' : 'black' }}>
      {props.friend.name}
    </li>
  );
}

Suggestion : 8

You might be thinking that we’d need a separate effect to perform the cleanup. But code for adding and removing a subscription is so tightly related that useEffect is designed to keep it together. If your effect returns a function, React will run it when it is time to clean up: We’ll continue this page with an in-depth look at some aspects of useEffect that experienced React users will likely be curious about. Don’t feel obligated to dig into them now. You can always come back to this page to learn more details about the Effect Hook. This requirement is common enough that it is built into the useEffect Hook API. You can tell React to skip applying an effect if certain values haven’t changed between re-renders. To do so, pass an array as an optional second argument to useEffect:

1._
import React, { useState, useEffect } from 'react';
function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:  useEffect(() => {    // Update the document title using the browser API    document.title = `You clicked ${count} times`;  });
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
2._
class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  componentDidMount() {    document.title = `You clicked ${this.state.count} times`;  }  componentDidUpdate() {    document.title = `You clicked ${this.state.count} times`;  }
  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}
3._
import React, { useState, useEffect } from 'react';
function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {    document.title = `You clicked ${count} times`;  });
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
5._
class FriendStatus extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         isOnline: null
      };
      this.handleStatusChange = this.handleStatusChange.bind(this);
   }

   componentDidMount() {
      ChatAPI.subscribeToFriendStatus(this.props.friend.id, this.handleStatusChange);
   }
   componentWillUnmount() {
      ChatAPI.unsubscribeFromFriendStatus(this.props.friend.id, this.handleStatusChange);
   }
   handleStatusChange(status) {
      this.setState({
         isOnline: status.isOnline
      });
   }
   render() {
      if (this.state.isOnline === null) {
         return 'Loading...';
      }
      return this.state.isOnline ? 'Online' : 'Offline';
   }
}
6._
import React, {
   useState,
   useEffect
} from 'react';

function FriendStatus(props) {
   const [isOnline, setIsOnline] = useState(null);

   useEffect(() => {
            function handleStatusChange(status) {
               setIsOnline(status.isOnline);
            }
            ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); // Specify how to clean up after this effect:    return function cleanup() {      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);    };  });
            if (isOnline === null) {
               return 'Loading...';
            }
            return isOnline ? 'Online' : 'Offline';
         }

Suggestion : 9

You can read JSX variables by putting them between curly braces, like {so}. Some JSX attributes are different than HTML attributes so that they don't conflict with JavaScript reserved words. For example, class in HTML translates to className in JSX. Note that multi-word attributes are in camelCase. Here, the <img /> tag's src attribute value is in curly braces. This is how JSX recognizes variables. React will see {logo}, know you are referring to the logo import on line 2 of our app, then retrieve the logo file and render it.

1._
const heading = <h1>Mozilla Developer Network</h1>;
2._
const header = (
<header>
   <h1>Mozilla Developer Network</h1>
</header>
);
3._
const header = <header>
   <h1>Mozilla Developer Network</h1>
</header>
5._
npx create - react - app moz - todo - react
6._
npx create - react - app moz - todo - react--use - npm