1

React has a few custom defined attributes. How can I define my own?

Why?

I have an Arc component, a few usage examples below:

<Arc startAngle="90" endAngle="270" stroke="hsl(38, 100%, 50%)" strokeWidth="0.5" />
<Arc startAngle="45" endAngle="90" fill="hsla(38, 100%, 50%, 0.2)" />
<Arc startAngle="0" endAngle="45" className="pie-slice" />

startAngle and endAngle attributes are required. All the other props are DOM properties that I just "proxy" to the root node.

var Arc = React.createClass({
    render: function() {
        return <path d={this.calcPath()}
            stroke={this.props.stroke}
            strokeWidth={this.props.strokeWidth}
            fill={this.props.fill}
            className={this.props.className}
        />
    },
    calcPath() {
        // ...
    }
});

I’m not happy with the boilerplate code for every property. I want to copy all the passed properties except startAngle and endAngle.

I came up with the following API:

var Arc = React.createClass({
    PROPS: {startAngle: true, endAngle: true},
    render: function() {
        return <path d={this.calcPath()} copyProps={cloneShallow(this.props, this.PROPS)}/>
    }
});

function cloneShallow(obj, exclude) {
    var result = {};
    var keys = Object.keys(obj);
    for (var i = 0; i < keys.length; i++) {
        var key = keys[i];
        if (!exclude.hasOwnProperty(key)) {
            result[key] = obj[key];
        }
    }
    return result;
}

I’d like to define copyProps attribute.


XSLT allows to tunnel attributes:

<path d={...}>
  <xsl:copy-of select="@*" />
</path>

I want something similar for React.js.

2 Answers 2

3

You can use this.transferPropsTo:

return this.transferPropsTo(<path .../>);

If you want to omit certain props, you can explicitly set them to null, e.g.

<path startAngle={null} />

but if the component you transfer the props to doesn't have such a prop anyway, it's not really necessary to do that.

See the documentation for more information.

Sign up to request clarification or add additional context in comments.

3 Comments

@FakeRainBrigand: Yep, but for now, that's the way to do it, until we get something new :)
It's likely that transferPropsTo will never go away entirely, but we're looking at adding some alternative solutions which are easier to reason about for most cases.
1

Starting React v0.12, transferPropsTo are replaced by JSX Spread Attributes:

return <path {...this.props}/>

1 Comment

Is there a nice way to exclude certain properties from a spread?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.