Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
21
rated 0 times [  27] [ 6]  / answers: 1 / hits: 174043  / 8 Years ago, thu, march 10, 2016, 12:00:00

I'm new to React and I'm puzzled on something kind of basic.



I need to append a component to the DOM after the DOM is rendered, on a click event.



My initial attempt is as follows, and it doesn't work. But it's the best thing I've thought to try. (Apologies in advance for mixing jQuery with React.)



    ParentComponent = class ParentComponent extends React.Component {
constructor () {
this.addChild = this.addChild.bind(this);
}

addChild (event) {
event.preventDefault();
$(#children-pane).append(<ChildComponent/>);
}

render () {
return (
<div className=card calculator>
<p><a href=# onClick={this.addChild}>Add Another Child Component</a></p>
<div id=children-pane>
<ChildComponent/>
</div>
</div>
);
}
};


Hopefully it's clear what I need to do, and I hope you can help me attain an appropriate solution.


More From » reactjs

 Answers
10

As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.



In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field



class HealthConditions extends React.Component {
constructor(props) {
super(props);


this.state = {
inputLinkClicked: false
}
}

handleAddSecondInput() {
this.setState({
inputLinkClicked: true
})
}


render() {
return(
<main id=wrapper className= data-reset-cookie-tab>
<div id=content role=main>
<div className=inner-block>

<H1Heading title=Tell us about any disabilities, illnesses or ongoing conditions/>

<InputField label=Name of condition
InputType=text
InputId=id-condition
InputName=condition
/>

{
this.state.inputLinkClicked?

<InputField label=
InputType=text
InputId=id-condition2
InputName=condition2
/>

:

<div></div>
}

<button
type=button
className=make-button-link
data-add-button=
href=#
onClick={this.handleAddSecondInput}
>
Add a condition
</button>

<FormButton buttonLabel=Next
handleSubmit={this.handleSubmit}
linkto={
this.state.illnessOrDisability === 'true' ?
/404
:
/add-your-details
}
/>

<BackLink backLink=/add-your-details />

</div>
</div>
</main>
);
}
}

[#62994] Monday, March 7, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
martina

Total Points: 101
Total Questions: 103
Total Answers: 111

Location: Seychelles
Member since Mon, Jun 28, 2021
3 Years ago
;