Render two separate components in React App - reactjs

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:
user click the button create user form
adding 1 component combination
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

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.

Related

Change of state in another component

How to solve the problem attached in the drawing?
I am talking about the best possible way of getting used without using redux.
When a button is pressed in a nested component, something has to change in another (it does not inherit from itself)
For example, in one component I choose the element and in the other I want to display details.
You can have a shared parent hold the state you want to change and pass to the first component while sending the onClick function to the other. Then, when one component changes the state through the onClick function, the changed prop will be passed on to the second component.
You should not change the state from one component via another component:
https://reactjs.org/docs/faq-state.html
props get passed to the component (similar to function parameters)
whereas state is managed within the component (similar to variables
declared within a function).
For "States" between components, you should use props from the store, via react-redux
First of all, I will suggest you to look into lift state up in react.
Now, how you'll do it: (just a pseudo example)
ParentComponent
onClick={this.onClick} stateProps={this.state.stateProps}
onClick() {
this.setState()
}
ComponentA
onClick={props.onClick}
ComponentB
console.log(props.stateProps)
The component will be used like: (again just a pseudo example)
<ParentComponent onClick={this.onClick} stateProps={this.state.stateProps}>
<ComponentA onClick={props.onClick} />
<ComponentB stateProps={props.stateProps} />
</ParentComponent>

How to mount/unmount react component instead of show/hide

I have a react question.
Basically, I have a component .
class Parent extends Component {
render () {
return (
<Child/>
)
}
}
Notice that the parent is not passing anything to child, rather the child has its own props and state mapped through the redux store. The is basically a modal which shows/hides and its actions are contained by different component. (Show/hide does not resets the state which is what I want every time I open the modal)
Since its not mounting/unmounting I dont have access to componentDidMount every time which I need.
My question is how to mount/unmount rather than show/hide since I dont care about preserving state values. I tried to do
{this.props.showChild && <Child/>}
but that did not work either.
I read about the react reconciliation algorithm just cannot figure out how does it apply here

State of child components in React

Should child components never have a state in React? I understand that state should be maintained by the "wrapper container" or parent container and it should have unidirectional flow. I have started with React and have a header container with upto 10 child components.
Let's say one of the child component is a Form with a submit button that can be enabled or disabled.
Should this child component not be able to have a constructor with state initialized for the button and be able to directly manipulate it or is it important that I maintain states as minute as this in the wrapper container "only"?
You should let the parent container manage the state of forms. I usually attach an onChange listener to each input and then when the submit button is clicked I call a function in the parent component to submit the value contained in the state for my form inputs. The form should only render inputs and do nothing else, basically a dumb component.
The purpose of React is providing a component system to front-end. It does not specify/enforce how state flow. People generally prefer state-less components because it is easier to share and distribute. However, front-end component can never be fully state-less + declarative.
In my opinion, you should feel free to use this.state to manage local state when you feel appropriate.

Set React component state from outside of component

I have a list of components and want to set each component as selected when the user clicks on it.
The flow looks like
Dashboard
⎿ MyList
⎿ MyItem -> onClick -> setState({active:true})
I've got the selected part done by using state but I'm left wondering how to deactivate all the other elements.
By definition, state is not accessible from outside the component.
And always copying props to state is not recommended.
In your component tree structure. you should set the selected item as state in the parent (not in the item).
And pass the selected Id to each item as a prop.
In the child render, you can do something like
let itemIsSelected = (this.props.itemId == this.props.selectedId);
And pass a method from parent to child, and then include that as:
onClick={() => this.props.setSelected(this.props.itemId)}
In the official docs, there is a good explanation on how to structure components. This may be helpful to determine whether something should be state or props, or whether stuff is better managed inside child or parent.
Dan Abramov mentions another clever way to access a state change from outside a component class. Technically the setState function still has to be called from within the component class anyway, so it's not REALLY outside the component, but this allows you to set the state of different components in the same fashion if you want, from the returned value of a function.
Basically, you can pass in a function into the setState() function, and the state will be set to the returned value of that function.
you can see his post here:
https://twitter.com/dan_abramov/status/824308413559668744?lang=en

How do I manage state on a React component that can have state changed from the parent or from events upon it?

I'm trying to make a custom checkbox component (a three-state, actually, but that's irrelevant except to say that I'm not just using an INPUT), and I'm not sure how I can make it able to change "checkedness" from clicks on itself and from a value-set coming down from the parent.
Currently, I have it working as a self-sufficient component that takes an onChange prop with the handler callback that it calls to send the value the parent component after clicks. It uses a state to store the checkedness, which is referenced by the display.
If it were merely a display of checkedness, with value being managed from outside, I'd use props, naturally. If it were only a self-sufficient checkbox component that took an initial value then only responded to clicks, I'd use state, like I am, but my problem is that I want it to be clickable to turn itself on and off, and allow the parent to turn it on and off as well.
I'm a beginner to React and the "React way of thinking" so I suspect I'm just approaching this wrong. I kind of get the impression that the proper way to do this would be for it to be a display-only component that passed clicks up to the parent to deal with, and in turn received props updates for value changes down from the parent, but that would make the component far less reusable, to my mind.
So how would I go about making a checkbox change from both internal and parent sources?
Relevant links are welcome, as well.
You may treat the checkbox as a dumb component, which means that it doesn't hold any internal states, but only receives data from outside via props and then render them. You can see the detailed definition of dumb components here.
Meanwhile, when the checkbox is clicked, such event will be handled by the component's parent, or event ancestors, this is called inverse data flow, which is described in Facebook's Thinking in React blog post.
Moreover, to decide which component should hold certain states, I find the following guidelines very useful:
Remember: React is all about one-way data flow down the component hierarchy. It may not be immediately clear which component should own what state. This is often the most challenging part for newcomers to understand, so follow these steps to figure it out:
For each piece of state in your application:
Identify every component that renders something based on that state.
Find a common owner component (a single component above all the components that need the state in the hierarchy).
Either the common owner or another component higher up in the hierarchy should own the state.
If you can't find a component where it makes sense to own the state, create a new component simply for holding the state and add it somewhere in the hierarchy above the common owner component.
The pseudo-code snippet:
const Checkbox = React.createClass({
// Propagate the event to parents
onClick(evt) {
if (this.props.handleClick) {
this.props.handleClick({checked: evt.target.value});
}
},
render() {
return (
this.props.checked ?
<Input onClick={this.onClick} type="checkbox" label="Checkbox" checked></Input> :
<Input onClick={this.onClick} type="checkbox" label="Checkbox"></Input>
);
}
});
const Container = React.createClass({
handleClick(evt) {
// Change the container's state, which eventually changes the checkbox's view via props.
this.setState({checked: evt.checked});
},
render() {
return (
<div><Checkbox checked={this.state.checked} handleClick={this.handleClick}></Checkbox></div>
);
}
});
You change it from only the parent.
class ParentComponent extends React.Component{
handleChildCheck(){
this.setState({
childChecked: !this.state.childChecked
})
}
render(){
return(
<ChildComponent checked={this.state.childChecked} handleCheck={this.handleChildCheck.bind(this)} />
)
}
}
Now if you wish to control the checked state from the <ChildComponent/> just call this.props.handleCheck() from the <ChildComponent/>
This way the controls will always be available within the <ChildComponent/> via this.props.handleCheck() within the <ParentComponent/> via this.handleChildCheck().

Resources