score:182
You can use mixed arrays with strings and JSX elements (see the docs here):
<MyComponent text={["This is ", <strong>not</strong>, "working."]} />
There's a fiddle here that shows it working: http://jsfiddle.net/7s7dee6L/
Also, as a last resort, you always have the ability to insert raw HTML but be careful because that can open you up to a cross-site scripting (XSS) attack if aren't sanitizing the property values.
score:-9
Have appended the html in componentDidMount using jQuery append. This should solve the problem.
var MyComponent = React.createClass({
render: function() {
return (
<div>
</div>
);
},
componentDidMount() {
$(ReactDOM.findDOMNode(this)).append(this.props.text);
}
});
score:0
Here is a solution that doesn't use the dangerouslySetInnerHTML
which is dangerous as the name says.
import { IntlProvider, FormattedMessage } from "react-intl";
<FormattedMessage
id="app.greeting"
description="Bold text example"
defaultMessage="Look here, I can include HTML tags in plain string and render them as HTML: <b>Bold</b>, <i>Italics</i> and <a>links too</a>."
values={{
b: (chunks) => <b>{chunks}</b>,
i: (chunks) => <i>{chunks}</i>,
a: (chunks) => (
<a class="external_link" target="_blank" href="https://jiga.dev/">
{chunks}
</a>
)
}}
/>
This should be rendered as:
Full example in https://jiga.dev/react-render-string-with-html-tags-from-props/
score:1
You could also use a function on the component to pass along jsx to through props. like:
var MyComponent = React.createClass({
render: function() {
return (
<OtherComponent
body={this.body}
/>
);
},
body() {
return(
<p>This is <strong>now</strong> working.<p>
);
}
});
var OtherComponent = React.createClass({
propTypes: {
body: React.PropTypes.func
},
render: function() {
return (
<section>
{this.props.body()}
</section>
);
},
});
score:1
In my project I had to pass dynamic html snippet from variable and render it inside component. So i did the following.
defaultSelection : {
innerHtml: {__html: '<strong>some text</strong>'}
}
defaultSelection object is passed to component from .js
file
<HtmlSnippet innerHtml={defaultSelection.innerHtml} />
HtmlSnippet component
var HtmlSnippet = React.createClass({
render: function() {
return (
<span dangerouslySetInnerHTML={this.props.innerHtml}></span>
);
}
});
score:1
Yes, you can it by using mix array with strings and JSX elements. reference
<MyComponent text={["This is ", <strong>not</strong>, "working."]} />
score:1
Adding to the answer: If you intend to parse and you are already in JSX but have an object with nested properties, a very elegant way is to use parentheses in order to force JSX parsing:
const TestPage = () => (
<Fragment>
<MyComponent property={
{
html: (
<p>This is a <a href='#'>test</a> text!</p>
)
}}>
</MyComponent>
</Fragment>
);
score:1
This question has already a lot of answers, but I had was doing something wrong related to this and I think is worth sharing:
I had something like this:
export default function Features() {
return (
<Section message={<p>This is <strong>working</strong>.</p>} />
}
}
but the massage was longer than that, so I tried using something like this:
const message = () => <p>This longer message is <strong>not</strong> working.</p>;
export default function Features() {
return (
<Section message={message} />
}
}
It took me a while to realize that I was missing the () in the function call.
Not working
<Section message={message} />
Working
<Section message={message()} />
maybe this helps you, as it did to me!
score:1
We can do the same thing in such a way.
const Child = () => {
return (
write your whole HTML here.
)
}
now you want to send this HTML inside another component which name is Parent component.
Calling :-
<Parent child={<child/>} >
</Parent>
Use Of Child:-
const Parent = (props) => {
const { child } = props;
return (
{child}
)
}
this work perfect for me.
score:2
@matagus answer is fine for me, Hope below snippet is helped those who wish to use a variable inside.
const myVar = 'not';
<MyComponent text={["This is ", <strong>{`${myVar}`}</strong>, "working."]} />
score:2
Do like this:
const MyText = () => {
return (
<>
This is <strong>Now</strong> working.
</>
)
}
then pass it as a props as:
<MyComponent Text={MyText} />
now you can use it in your component:
const MyComponent = ({Text}) => {
return (
<>
// your code
{<Text />}
// some more code
</>
)
}
score:3
You can do it in 2 ways that I am aware of.
1- <MyComponent text={<p>This is <strong>not</strong> working.</p>} />
And then do this
class MyComponent extends React.Component {
render () {
return (<div>{this.props.text}</div>)
}
}
Or second approach do it like this
2- <MyComponent><p>This is <strong>not</strong> working.</p><MyComponent/>
And then do this
class MyComponent extends React.Component {
render () {
return (<div>{this.props.children}</div>)
}
}
score:3
Parser from html-react-parser is a good solution. You just have to
- install it with npm or yarn
- import Parser from 'html-react-parser';
call it with :
<MyComponent text=Parser("This is <strong>not</strong> working.") />
and it works well.
score:4
You can successfully utilize React fragments for this task. Depending on the React version you use, you can use short syntax: <>
or the full tag: <React.Fragment>
. Works especially well if you don't want to wrap entire string within HTML tags.
<MyComponent text={<>Hello World. <u>Don't be so ruthless</u>.</>} />
score:6
You can use the <></>
Fragments to pass the HTML in the props.
<MyComponent text={<>"This is <strong>not</strong> working."</>} />
Reference: https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html#jsx-fragment-syntax
score:7
For me It worked by passing html tag in props children
<MyComponent>This is <strong>not</strong> working.</MyComponent>
var MyComponent = React.createClass({
render: function() {
return (
<div>this.props.children</div>
);
},
score:7
Set the text prop type to any and do this:
<MyComponent text={
<React.Fragment>
<div> Hello, World!</div>
</React.Fragment>
}
/>
score:8
<MyComponent text={<span>This is <strong>not</strong> working.</span>} />
and then in your component you can do prop checking like so:
import React from 'react';
export default class MyComponent extends React.Component {
static get propTypes() {
return {
text: React.PropTypes.object, // if you always want react components
text: React.PropTypes.any, // if you want both text or react components
}
}
}
Make sure you choose only one prop type.
score:8
On a client-side react application, there are a couple of ways of rendering a prop as a string with some html. One safer than the other...
1 - Define the prop as jsx (my preference)
const someProps = {
greeting: {<div>Hello<a href="/${name_profile}">${name_profile}</a></div>}
}
const GreetingComopnent = props => (
<p>{props.someProps.greeting}</p>
)
• The only requirement here is that whatever file is generating this prop needs to include React as a dependency (in case you're generating the prop's jsx in a helper file etc).
2 - Dangerously set the innerHtml
const someProps = {
greeting: '<React.Fragment>Hello<a href="/${name_profile}">${name_profile}</a></React.Fragment>'
}
const GreetingComponent = props => {
const innerHtml = { __html: props.someProps.greeting }
return <p dangerouslySetInnerHtml={innerHtml}></p>
}
• This second approach is discouraged. Imagine an input field whose input value is rendered as a prop in this component. A user could enter a script tag in the input and the component that renders this input would execute this potentially malicious code. As such, this approach has the potential to introduce cross-site scripting vulnerabilities. For more information, refer to the official React docs
score:16
You can use dangerouslySetInnerHTML
Just send the html as a normal string
<MyComponent text="This is <strong>not</strong> working." />
And render in in the JSX code like this:
<h2 className="header-title-right wow fadeInRight"
dangerouslySetInnerHTML={{__html: props.text}} />
Just be careful if you are rendering data entered by the user. You can be victim of a XSS attack
Here's the documentation: https://facebook.github.io/react/tips/dangerously-set-inner-html.html
score:23
From React v16.02 you can use a Fragment.
<MyComponent text={<Fragment>This is an <strong>HTML</strong> string.</Fragment>} />
More info: https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html
score:153
Actually, there are multiple ways to go with that.
You want to use JSX inside your props
You can simply use {} to cause JSX to parse the parameter. The only limitation is the same as for every JSX element: It must return only one root element.
myProp={<div><SomeComponent>Some String</div>}
The best readable way to go for this is to create a function renderMyProp that will return JSX components (just like the standard render function) and then simply call myProp={ this.renderMyProp() }
You want to pass only HTML as a string
By default, JSX doesn't let you render raw HTML from string values. However, there is a way to make it do that:
myProp="<div>This is some html</div>"
Then in your component you can use it like that:
<div dangerouslySetInnerHTML=myProp={{ __html: this.renderMyProp() }}></div>
Beware that this solution 'can' open on cross-site scripting forgeries attacks. Also beware that you can only render simple HTML, no JSX tag or component or other fancy things.
The array way
In react, you can pass an array of JSX elements. That means:
myProp={["This is html", <span>Some other</span>, "and again some other"]}
I wouldn't recommend this method because:
- It will create a warning (missing keys)
- It's not readable
- It's not really the JSX way, it's more a hack than an intended design.
The children way
Adding it for the sake of completeness but in react, you can also get all children that are 'inside' your component.
So if I take the following code:
<SomeComponent>
<div>Some content</div>
<div>Some content</div>
</SomeComponent>
Then the two divs will be available as this.props.children in SomeComponent and can be rendered with the standard {} syntax.
This solution is perfect when you have only one HTML content to pass to your Component (Imagine a Popin component that only takes the content of the Popin as children).
However, if you have multiple contents, you can't use children (or you need at least to combine it with another solution here)
Source: stackoverflow.com
Related Query
- React - How to pass HTML tags in props?
- How to pass a html template through props to a react component?
- How to pass props as a HTML tag to react element in dash plotly
- How to query by text string which contains html tags using React Testing Library?
- How to pass all other props to react class?
- React - How to pass props to a component passed as prop
- How to pass several props in spread operator in react
- How to pass props to component inside a React Navigation navigator?
- React useReducer Hook fires twice / how to pass props to reducer?
- How do I pass an object containing props to React component?
- React bind in constructor, how to pass parameters to props
- How to pass props to react component that wrapped in variable
- how to pass props to the route when using react router <Link>
- How to pass props of React component to styled component
- React Native: How to pass props to 'routeMapper' of 'Navigator.NavigationBar'?
- How to pass additional props throughout a Route element that has parameters in a Typescript based React Web Application
- How to pass props into jest test in React
- How to pass rest of props to react component while also having required props defined in an interface
- How to pass props through useRoutes in react hook router?
- How to pass from a react props to a sass variable?
- React Hook Forms How to pass the errors as a props using Typescript
- How to let string coming with HTML tags to be rendered in React js?
- How to pass props to React Big Calendar custom components?
- How to render raw HTML content to React pass via props?
- How to pass props from template to react root node?
- React Data Table Expandable Rows : how to pass additional Props
- How to pass dynamic props to a React component that accepts a union of objects as its type?
- In how many ways we can pass props to all child components in react
- React TS - How to pass props from a parent component to a deeply nested child
- How can I replace Markdown-rendered HTML tags with React components?
More Query from same tag
- How to change the background-color when scrolling?
- Warning: Encountered two children with the same key, `[object Object]`
- Export React.JS variable and use in other file
- diaplays same data in react js, if condition not working or working but map function takes all value without sorting
- Globals with Browserify / ReactJS
- Slice vs filter in redux delete action
- IntersectionObserver with React & Hooks
- How to make onClick event in NavBar in react?
- How would I return an error message upon a failed search in react.js
- How to change value of all checkboxes in react?
- REACT Uncaught TypeError .then is not a function
- How to query graphql in react typescript
- scroll into view after routing in react
- Is there any slider for react material-ui chips?
- How does dispatching a action creator function work?
- react-scss : display problem of an <h1> with blur and transform, on "EDGE" only
- How do I create multiple pages within my domain using React?
- How to create seperate component just for routes using react router?
- Component not re-rendering when context is updated
- Can't Connect to MongoDB using Mongoose
- Add style from props to existing component styles in React Native
- React event.target is not the element I set event Listener on
- ReactJS: Error while solving memory leak using makeCancellable method
- Why I can't see props in intellisense when using styled-system with styled components?
- Webpack throws error on React image import
- Pass existing record record/value to Create Component
- API call in ReactJS and setting response to state
- Module not found: Error: Can't resolve 'crypto', webpack < 5 used to include polyfills for node.js core modules by default
- Axios request in react
- redux-form fields parameters are empty