In React, you can do the following:
export const Button = ({ icon, children, ...props }) => {
const Icon = () => (
icon ? <FontAwesomeIcon icon={["fal", "check"]} className={iconPositionClass}/> : null
);
return (
<BsButton children={children} {...props}>
{iconPosition === "left"
? <><Icon/>{children}</>
: <>{children}<Icon/></>
}
</BsButton>
);
};
I can create another component inside the first one, in this case, <Icon />, and then conditionally render it inside the first one, <Button />.
With Vue, however, it's not like that, because there is no return. There's just a template tag, and while you can create a function in the <script> tag, that function cannot return html.
I know that I can re-create the above code using v-if and v-else for the actual element that I want to be rendered, but that just means that I have to repeat the code inside the <template>. It feels too repetitive.
Is there a way to re-create the React way of doing it in Vue?
I'm trying to pass a ref to be read inside of emotion component (similar to styled-components)
But receving the error Cannot find name 'ref'
What should I do in order to be able to access the ref inside the emotion component?
const Label = styled('p')<{ ref: React.MutableRefObject<null> }>({
fontsize: ref.current...,
});
export const NodeDisplayer = ({ data }) => {
const size = useRef(null);
return (
<>
<Label ref={size} id="title">
</Label>
</>
What are you trying to do? Why would a component need to access its own DOM node to determine its styling? I doubt it will work properly.
But to answer your question, the ref prop is special in React so it isn't accessible in the props, but nothing prevents you from also adding it as a different prop:
<Label ref={size} myRef={size} id="title">
Then you should be able to access myRef.
You cannot get a reference to a component function, because it does not exist in the DOM. You need to reference the HTML element, which you might as well do in the child. And since the ref will not be populated until after the component has rendered, you need to use useEffect to get the referenced node.
function Label() {
const ref = useRef<HTMLParagraphElement>(null);
const [style, setStyle] = useState<CSSProperties>({});
useEffect(() => setStyle({ fontSize: ref.current.clientWidth + 'px' }), []);
return (
<p ref={ref} style={style}>
Hi
</p>
);
}
export const NodeDisplayer = () => <Label></Label>
I played with React for several years, still confused with mount/unmount mechanism in some case.
Since mount/unmount is the place to perform side effect, I do not want them to be invoked randomly. So I need to figure out how they work. As far as I can understand currently, when the virtual dom do not present in real dom, it tend to be unmounted. However, it seems not the whole story, and I can not reason it about
function TestMount(props) {
useEffect(() => {
console.log("componentDidMount", props.name);
return () => {
console.log("componentWillUnount", props.name);
};
}, []);
return <h1>Test content {" " + JSON.stringify(props.name)}</h1>;
}
function Update({ click }) {
return <button onClick={click}>Update</button>;
}
function App() {
const [count, setCount] = useState(0);
const Component = name => <TestMount name={name} />;
return (
<div className="App">
<h1>{count}</h1>
<Component name="one" />
{Component("two")}
<Update click={() => setCount(x => x + 1)} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Component One is remount overtime the app render while Component two not?Why this happen?
Component is a new function each time App is rendered, so <Component name="one" /> is remounted each time too, they are considered different components.
The result of Component("two") call is <TestMount name={"two"} />, TestMount stays the same each time App is rendered, so it's not remounted.
Component is invalid component for what it's used for, to pass name string as name prop to TestMount component because name parameter is not a string but props object when Component is used like <Component name="one" />. name => <TestMount name={name} /> is render function, it's preferable to name it accordingly like renderTestMount for clarity because components aren't supposed to be called directly like Component("two").
In case a function is supposed be used as component or render function interchangeably, the signature should be changed to ({ name }) => <TestMount name={name} />.
The expected behaviour could be achieved for <Component name="one" /> by memoizing Component:
const Component = useCallback(({ name }) => <TestMount name={name} />, []);
But since Component doesn't depend on App scope, a correct way is to define it outside:
const Component = ({ name }) => <TestMount name={name} />;
function App() {...}
For instance, this is the reason React Router Route has separate component and render props for a component and render function. This allows to prevent unnecessary remounts for route components that need to be defined dynamically in current scope.
The key to such issue is the difference between the React Component and React element, put shortly React is smart with element not Component
Component vs element
Component is the template used to create element using <> operation. In my prospective, <> is pretty much like new operator in OOP world.
How React perform update between renders
Every time the render method(or functional component) is invoked. The new element is created using <>, however, React is smart enough to tell the element created between renders are actually the same one, i.e. it had been created before and can be reused as long as the element is created by the same Component
How about different Component
However when the identity of the Component using to generate element changes(Even if the Components look same), React believes something new come though, so it remove(unmount) the previous element and add(mount) the new one. Thus componentDidMount or componentWillUnmount is invoked.
How is confusing
Think we got a Component and when we generate element using <Component /> react can tell the same elements because they are generated by the same Component
However, HOCComponent=()=><Component />; element= <HOCComponent />, every time element is generated, it used a different Component. it is actually a HOC constructed dynamically. Because the HOC is created dynamically inside render function, it can be confusing on the first glance.
Is that true
I never found any offical document about the idea above.However the code below is enough to prove
function TestMount(props) {
useEffect(() => {
console.log("componentDidMount", props.name);
return () => {
console.log("componentWillUnount", props.name);
};
}, []);
return <h1>Test content {" " + JSON.stringify(props.name)}</h1>;
}
function Update({ click }) {
return <button onClick={click}>Update</button>;
}
let _Component;
function cacheComponent(C) {
if (C && !_Component) {
_Component = C;
}
return _Component || null;
}
const CacheComponent2 = once(({ name }) => <TestMount name={name} />, []);
function App() {
const [count, setCount] = useState(0);
// can be used as a HOC of TestMount or a plain function returnnung a react element
const Component = name => <TestMount name={name} />;
const CacheComponent1 = cacheComponent(Component);
const CacheComponent3 = useCallback(
({ name }) => <TestMount name={name} />,
[]
);
return (
<div className="App">
<h1>{count}</h1>
{/* used as HOC */}
<Component name="one" />
{/* used as function returnning the element */}
{Component("two")}
<CacheComponent1 name="three" />
<CacheComponent2 name="four" />
<CacheComponent3 name="five" />
<Update click={() => setCount(x => x + 1)} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Also the code above provide three different ways to avoid the undesired mount/unmount. All the solutions are cache the identity of the HOC somehow
I want to do something like this.
In the parent component
<child tag={h1}/>
In the child component
<this.props.tag />
The problem "Unresolved variable or type div" throwing When i pass one of html components ( tags ) like ( div , h1, ext. )
UPDATED:
Yes, we can pass HTML tag as a prop. There are several ways based on what you want.
Passing tag as a prop
<ChildComponent tag="h1" />
And inside child component, we can use the tag as below.
const Child = ({ tag: Tag}) => (
<Tag>Hello World</Tag>
)
By setting dangerouslySetInnerHTML
<Child tags="<h1>Hello world</h1>" />
Inside child component:
const Child = props => <div dangerouslySetInnerHTML={{ __html: props.tags.outerHTML }}/>
Here is what you should know about dangerouslySetInnerHTML. In short, this exposes XSS attack.
This one is not related to passing as a prop. But you might wanna consider
If you are doing SEO task related (maybe nextjs) and you need to render conditional tag (sometimes h2 and sometimes h3). Then you can do as follow!
Conditional Statement
// Parent
const Parent = () => <Child isH3Tag />
// Child
const Child = ({ isH3Tag = false, children }) => isH3Tag ? <h3>{children}</h3> : <h2>{children}</h2>;
Here is a demo. https://codesandbox.io/s/8x65l707yj
JSX expressions must start with a cap, for example <Elment />
In your case, when you want to pass tag names, use createElement:
<div>
{React.createElement(this.props.tag, {children: <content>, prop1: <v1>, ...})}
<div>
Another alternative will be to use recompose#componentFromProp
You can pass tag as children, from parent Component like this:
In the parent component:
<Child> <h1></h1> </Child>
In the child component you can access like:
render() {
return (
{this.props.children}
)
}
I want to be able to pass text with HTML tags, like so:
<MyComponent text="This is <strong>not</strong> working." />
But inside of MyComponent's render method, when I print out this.props.text, it literally prints out everything:
This is <strong>not</strong> working.
Is there some way to make React parse HTML and dump it out properly?
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.
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)
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
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
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
<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.
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${name_profile}</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${name_profile}</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
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>
);
},
Set the text prop type to any and do this:
<MyComponent text={
<React.Fragment>
<div> Hello, World!</div>
</React.Fragment>
}
/>
Example
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>)
}
}
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>.</>} />
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.
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
</>
)
}
#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."]} />
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>
);
}
});
Plunkr example
react doc for dangerouslySetInnerHTML
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>
);
},
});
Yes, you can it by using mix array with strings and JSX elements. reference
<MyComponent text={["This is ", <strong>not</strong>, "working."]} />
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>
);
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!
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.
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/
This works for me
<MyComponent text={<>some text <strong>bold text</strong> and more.</>} />
Also if you want to pass variable here, you can try like this
<MyComponent text={<>My name is {variableName}. <strong>Bold text</strong> normal text</>} />
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);
}
});