React JSX - dynamic html attribute - reactjs

In JSX, we can indicate attribute value dynamically like:
<div className={this.state.className}>This is a div.</div>
Is it possible to indicate attribute (including attribute name and attribute value) dynamically? Like:
const value = emptyValue ? "" : "value='test'";
<input {value} />
That means, once emptyValue is true, "input" tag should not include "value" attribute (value="" is different from no value attribute, as one is show empty in input field, another is show existing text in input field).

ES6 object expansion only works for objects. Therefore to generate a dynamic attribute, try something like this:
const value = emptyValue ? {} : { value: 'test' }
<a {...value} ></a>
Note value will always be an object.

you can insert whole element in if statement in render function, but before return like this:
render() {
var input = (<input />);
if (!emptyValue) {
input = (<input value='test'/>)
}
return (
<div>
{input}
</div>
)
}

Related

Add custom CSS class via variable to returned jsx

I've created a custom component which essentially returns html markup in order to display content based on the values passed to the component. Here's a simplified version for brevity:
interface ContainerProps {
position?: string;
content?: string;
class?: string;
}
const CardContainer: React.FC<ContainerProps> = ({ position = "right", content = "n/a", class = "" }) => {
if ( position.trim().toLowerCase() === "right" ) {
return <><div className="ion-float-right" >{content}</div><div className="clear-right"></div></>
} else if ( position.trim().toLowerCase() === "left" ) {
return <div className="ion-float-left">{content}</div>
} else {
return null
}
};
export default CardContainer;
This works great, but I now need to be able to pass a css class name to the component. However, I can't work out how to add the "class" prop to the returned html/jsx.
I tried various code such as below. However, in all cases the code was output as actual html rather than the value of the prop:
return <div className="ion-float-left" + {class}>{content}</div>
return <div className="ion-float-left {class}" >{content}</div>
return <div className="ion-float-left class">{content}</div>
I also tried a few other random things in desperation and these typically cause a compilation error. What is the best way to achieve the intended result eg:
return <div className="ion-float-left myClassNameHere">{content}</div>
its like inserting a string inside another or adding them together. You can use classname={"yourclasse" + theDynamicClass} or className={yourClass ${dynamicClass}} (inbetween ``)
return <div className=` ion-float-left ${class}``>{content}

How can I use dataset with cloneelement?

How can I set a data attribute on an element when using cloneelement?
I've tried it this way.
const clonedItem = React.cloneElement(item, {
dataset: { "data-test": 123 },
dataTest: 123,
})
But that doesn't set any attribute in my html...
May be you are storing a custom component in item variable i.e
let item = <ItemComponent />.
Just store html element in item variable i.e
let item = <div><h1>Hello</h1></div>
And that will set attribute in div element.
If you use custom component, you need to use the props passed in the component.
i.e ItemComponent will be as
function ItemComponent({dataTest}){
return (
<div dataTest={dataTest}>
<h1>Hello</h1>
</div>
);
}
The one that worked for me is by settings the key as string
const clonedItem = React.cloneElement(item, {
'data-test': 123
})

How to conditionally set HTML attributes in JSX using reason-react?

I want to render an HTML checkbox whose checked state is controlled by data.
Give a stateless component that receives an item type { label: string, checked: bool},
Like so:
let component = ReasonReact.statelessComponent("TodoItem");
let make = (~item, _children) => {
render: _self => {
<li> <input type_="checkbox" {/*looking for something like this*/ item.checked ? "checked" : "" /* doesn't compile */}/> {ReasonReact.string(item.label)} </li>
}
}
How do I add the presence of the attribute checked to the input tag based on the item.checked == true condition?
As #wegry said in a comment, it seems to fit your use case better to just pass the value directly since item.checked already is a boolean, and checked takes a boolean.
But to answer more generally, since JSX attributes are just optional function arguments under the hood, you can use a neat syntactic trick to be able to explicitly pass an option to it: Just precede the value with ?. With your example:
let component = ReasonReact.statelessComponent("TodoItem");
let make = (~item, _children) => {
render: _self => {
<li> <input type_="checkbox" checked=?(item.checked ? Some(true) : None) /> {ReasonReact.string(item.label)} </li>
}
}
Or, to give an example where you already have an option:
let link = (~url=?, label) =>
<a href=?url> {ReasonReact.string(label)} </a>
This is documented in the section titled Explicitly Passed Optional on the Function page in the Reason docs.

Concatenate a variable to an HTML tag

I am trying to show an arrow next to a variable only if this variable is not null. The variable in question is flight.c_tof.
render() {
const items = this.state.flights.map((flight) =>
<tr key={flight.uid}>
<td>{flight.c_tof == null ? null : flight.c_tof + <span className="icon-arrow-right icon-small"></span>}</td>
</tr>
)
return ...{items}...
}
This outputs something like: LPPD[object Object]
If I remove flight.c_tof +, then it shows that arrow as it should. How can I concatenate that variable?
Change your td to
<td>{flight.c_tof === null ? null : <span>{flight.c_tof} <span className="icon-arrow-right icon-small"> </span></span>}</td>
You can only output one element as the result of the conditional. So, when you remove the flight.c_tof + , the output is just the span with the icon and it shows up fine. But when you add the flight.c_tof + it is not a valid html element and shows up as a javascript object.
Edited after #DaveNewton's comment:
You can create a component like
const ArrowField=(props)=>{
return (<div>
{props.data}
<span className="icon-arrow-right icon-small"></span>
</div>);
}
and then use it like
<td>{flight.c_tof === null ? null : <ArrowField data={flight.c_tof} />}</td>

Dynamic attribute in ReactJS

I want to dynamically include/omit the disabled attribute on a button element. I have seen plenty of examples of dynamic attribute values, but not of attributes themselves. I have the following render function:
render: function() {
var maybeDisabled = AppStore.cartIsEmpty() ? "disabled" : "";
return <button {maybeDisabled}>Clear cart</button>
}
This throws a parse error because of the "{" character. How can I include/omit the disabled attribute based on the (boolean) result of AppStore.cartIsEmpty()?
The cleanest way to add optional attributes (including disabled and others you might want to use) is currently to use JSX spread attributes:
var Hello = React.createClass({
render: function() {
var opts = {};
if (this.props.disabled) {
opts['disabled'] = 'disabled';
}
return <button {...opts}>Hello {this.props.name}</button>;
}
});
React.render((<div><Hello name="Disabled" disabled='true' />
<Hello name="Enabled" />
</div>)
, document.getElementById('container'));
By using spread attributes, you can dynamically add (or override) whatever attributes you'd like by using a javascript object instance. In my example above, the code creates a disabled key (with a disabled value in this case) when the disabled property is passed to the Hello component instance.
If you only want to use disabled though, this answer works well.
I'm using React 16 and this works for me (where bool is your test):
<fieldset {...(bool && {disabled:true})}>
Basically, based on the test (bool) you return an object with the conditional attributes or you don't.
Also, if you need to add or omit multiple attributes you can do this:
<fieldset {...(bool && {disabled:true, something:'123'})}>
For more elaborate attribute managed I suggest you prefab the object with (or without) the attributes outside of JSX.
You can pass a boolean to the disabled attribute.
render: function() {
return <button disabled={AppStore.cartIsEmpty()}>Clear cart</button>
}
function Test() {
return (
<div>
<button disabled={false}>Clear cart</button>
<button disabled={true}>Clear cart</button>
</div>
);
}
ReactDOM.render(<Test />, document.querySelector("#test-container"));
console.log(Array.from(document.querySelectorAll("button")));
<script crossorigin src="https://unpkg.com/react#17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#17/umd/react-dom.development.js"></script>
<div id="test-container"></div>
Far cleaner than the accepted solution is the solution which AnilRedshift mentioned, but which I'll expand on.
Simply put, HTML attributes have a name and a value. As a shorthand, you can use the name only for "disabled", "multiple", etc. But the longhand version still works, and allows for React to work in it's preferred way.
disabled={disabled ? 'disabled' : undefined} is the most legible solution.
The version I used was:
<button disabled={disabled ? 'disabled' : undefined}>
Click me (or dont)
</button>
More cleaner way of doing dynamic attributes which works for any attributes is
function dynamicAttributes(attribute, value){
var opts = {};
if(typeof value !== 'undefined' && value !== null) {
opts['"'+attribute+'"'] = value;
return opts;
}
return false;
};
Call in your react component like following
<ReactComponent {...dynamicAttributes("disabled",false)}
{...dynamicAttributes("data-url",dataURL)}
{...dynamicAttributes("data-modal",true)} />
Tips :
You could have dynamicAttributes function in a common place/utilities and
import it to use it across all components
you could pass value as null to not render dynamic attribute
A simple and clean way of doing it
<button {...disabled && {disabled: true}}>Clear cart</button>
disabled should come from props like this
<MyComponent disabled />
You can find something similar to this at the documentation.
https://facebook.github.io/react/docs/transferring-props.html
In your case could be something like this
function MyComponent(props) {
let { disabled, ...attrs } = props;
if (disabled) {
// thus, it will has the disabled attribute only if it
// is disabled
attrs = {
...attrs,
disabled: true
}
};
return (
<button {...attrs}>MyLabel</button>
)
}
This code is using ES6, but I thing you got the idea.
This is cool because you can pass many others attributes to this component and it will still work.
First you can simply check
<button disabled={true}>Button 1</button>
<button disabled={false}>Button 2</button>
Note: **disabled value is not String, it should be Boolean.
Now for dynamic. You can simply write
<button type="button" disabled={disable}
onClick={()=>this.setSelectValue('sms')} >{this.state.sms}</button>
As you can see I am using disabled property and in curly brackets it can be local variable/state var.
The variable disable contains values true/false.
In case others come here for attributes other than disabled, e.g., custom attributes like data-attr, one can assign empty string "" as the value in the object to be spread to eliminate the value of the attribute. With the attribute name only available on the resulted HTML.
For example:
<div {...(trueOrFalse && { [`data-attr`]: "" })}></div>
Furthermore, if you wish the name of the attribute being dynamic too. Due to template strings support string interpolation, you can put state into it to make the name of attribute dynamic.
<div {...(trueOrFalse && { [`${state}`]: "" })}></div>
This could work, problem with disabled is one could not simply set boolean for it.
if(AppStore.cartIsEmpty()){
return "<button disabled>Clear cart</button>"
}
else
{
return "<button>Clear cart</button>"
}

Resources