BrokenCoin
BrokenCoin

Reputation: 97

Render two separate components in React App

I am not experienced enough React delevoper yet, so i am having issue with rendering 2 separate components, which are comunicate with each other. So the main task is simple:

Btw i want to provide to user the possibility to create as much component combination as he will want. What pattern should i look for? I don't understand how to create two communicating components inside different parent containers.

Here is gif for better understanding

Upvotes: 0

Views: 556

Answers (1)

Nick Kinlen
Nick Kinlen

Reputation: 1406

If Main is a component and Sidebar is a component you want to store state in Main and pass props to Sidebar.

Make Main a stateful class based component with a constructor function and store something like this:

this.state = {
    addInput: false  
}

Then in Main write a click handler. When the user clicks a button set addInput to true.

function addComponent() => {
    this.setState({
       addInput: !this.state.addInput
    })
}

Add an onClick event handler to the button like this:

<input type="button" onClick={this.addComponent()} />

Then inside Main pass props to Sidebar:

<SideBar addInput={this.state.addInput} />

Then inside Sidebar you can use props and a ternary to decide whether or not to display the input section based on whether addInput is true or false.

I wrote this quick and it's a basic rundown. Check out the React props docs for more information.

Instead of using a boolean inside Main's state you could also use a number and dictate how many input boxes show up in Sidebar based on the number value.

Here is an example that I wrote showing another person how to pass props in a React component. Check it out and you'll see an example of passing props to a child component. Look at Parent and Child components and see how props are passed and also state being updated by an onClick event.

Upvotes: 1

Related Questions