Ad
ReactJS: Programmatically Change Component Tag With JSX
I am making a conditional component that returns <a>
if href is defined and returns <div>
if not. I am doing this way:
const Label = ({children, ...other}) => {
let component;
if (other.href)
component =
<a {...other}>
{ children }
</a>
else
component =
<div {...other}>
{ children }
</div>
return component;
}
export default Label
There is any way to make this component by only changing the tag name? I know that if I use the manual way of creating compontents (React.createElement
) I can do this by changing the first argument passed, for it's a string. But with JSX it's a little different. I though something like
let component =
<{tag} {...other}>
{ children }
</{tag}>
Is it possible?
Ad
Answer
something like this?
const Label = ({children, ...other}) => {
let component;
if (other.href) {
component = <a {...other}>{ children }</a>;
} else if (other.tag) {
const Tag = other.tag;
component = <Tag {...other}>{ children }</Tag>;
} else {
component = <div {...other}>{ children }</div>;
}
return component;
}
ReactDOM.render(
<Label target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="#">Hello World</Label>,
document.getElementById('root')
);
ReactDOM.render(
<Label>Not a Link</Label>,
document.getElementById('rootTwo')
);
ReactDOM.render(
<Label tag="p">Paragraph</Label>,
document.getElementById('rootThree')
);
Working demo:, https://jsfiddle.net/tgm4htac/
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad