What is the best way to have variable attributes in JSX?

Hope my question is clear, I'm basically looking for a way to dynamically attach attributes to JSX input.

<input type="text" {variableAttribute}={anotherVariable} />

Is it possible like this without overriding how JSX compiles JS into plain HTML?

+4
source share
2 answers

You can initialize the object using the name of the computed property , and then use the JSX Spread Attributes to convert it to an attribute:

const DemoComponent = ({ variablePropName, variablePropValue }) => { 
    const variableAttribute = { [variablePropName]: variablePropValue };
    return (
        <input type="text" { ...variableAttribute } />
    );
};
+10
source

You cannot do it the way you do. You must define your attributes as an object and pass this as propagation attributes.

, , .

.

var Hello = React.createClass({
      render: function() {
        
        var opt = {}
        opt['placeholder'] = "enter text here";
        return (<div>
        Hello {this.props.name}
        <div>
        	<input type="text" {...opt}/>
        </div></div>);
      }
    });
    
    ReactDOM.render(
      <Hello name="World" />,
      document.getElementById('container')
    );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="container">
    <!-- This element contents will be replaced with your component. -->
</div>
Hide result

DOCS

+1

Source: https://habr.com/ru/post/1649318/


All Articles