J. Doe
J. Doe

Reputation: 91

Add children to React element

How can I add a child to a React component. this.props.children seems to be read-only so can't mutate it directly.

Let's say I have

var myComponent = <MyComponent someProp="foo"><h1>heading</h1><h2>another heading</h2></MyComponent>

and I'd like to add <p>some text</p> as a third child to it.

I'd like to accomplish this:

var newChild = <p>some text</p>
myComponent.props.children.add(newChild)

so that the result would be

<MyComponent someProp="foo"><h1>heading</h1><h2>another heading</h2><p>some text</p></MyComponent>

(obviously the add function doesn't exist but the question is what to do instead)

Upvotes: 6

Views: 11827

Answers (2)

E_net4
E_net4

Reputation: 29982

The children prop represents the content inserted between the tags of a JSX element (see docs), and is not supposed to be modified directly. In fact, attempting to perform modifications on any content inside of this.props is usually unthinkable.

To address your particular problem, you seem to wish to define what children are added to a component, as in something like this:

// parent component's render method
render() {
  const elements = ...; //build up an array of elements
  return (<MyComponent someProp="foo">
    <h1>heading</h1>
    <h2>another heading</h2>
    {elements}
  </MyComponent>)
}

The root element of type MyComponent would then know how to use these children for a proper render, which are made available in this.props.children. If this component needs to actively trigger the inclusion of text, then you could either include a text change callback as a prop to MyComponent, or just use component state (thus refraining from using the children for that paragraph at all).

Upvotes: 2

amritdevilo
amritdevilo

Reputation: 86

Keep a state that has all the children to the component.

Try adding to the state instead of the props, and in render write:

render() {
return ({<div>this.state.children.map((child) => {return <child as jsx>;}}</div>);

Upvotes: 1

Related Questions