Reputation: 1527
Lets say i have this react component refering to a TextInput. I want this component to be a
<input type="text">
and a <textarea>
as well, but with no ifs on it, as being passed throw props, however my renderer got extra stuff on the element as follows:
render() {
return (
<label>
<strong>{this.props.name}</strong>
<input type="text" ref={ component => { this.input = component; } } name={this.props.name} onChange={this.handleChange} value={this.state.value} />
</label>
)
}
My original idea was doing something like this
myInputProps = { type: (<input type="text"/>) }
So in my element i woul render this simply as
{this.props.type}
However how could i pass all those extra stuff to the element such as the ref, name, onchange etc ? What would be a good aproach on this problem ? I could do some ifs and check what should i render depending on the component state etc, but i`m not sure that would be the best.
Upvotes: 1
Views: 637
Reputation: 67296
I'd advocate using separate <TextInput>
and <TextArea>
components, but if you really need the flexiblity, use render props:
Using a render
prop:
render() {
const props = {
ref: component => this.input = component,
name: this.props.name,
onChange: this.handleChange
};
return (
<label>
<strong>{this.props.name}</strong>
{ this.props.render(props) }
</label>
)
}
Then use it like:
<TextInput name="foo" render={ props => <input ...props /> } />
Upvotes: 0
Reputation: 4862
render() {
return (
<label>
<strong>{this.props.name}</strong>
{this.props.children}
</label>
)}
Upvotes: 0
Reputation: 6171
What you need is:
render() {
var input = this.props.type;
input.props = {
...input.props,
ref: (component) => { this.input = component;},
onChange: this.handleChange,
value: this.state.value
};
return (
<label>
<strong>{this.props.name}</strong>
{input}
</label>
)
}
Upvotes: 1