A
A
Andrey2017-03-06 22:36:09
React
Andrey, 2017-03-06 22:36:09

How to correctly pass one react component to another?

I'm doing a project for educational purposes with React.
I want to make a pop-up window - a react-component - into which other components could be passed.
If the user clicked the "Register" button, a window with the registration form appears, If the user clicked the "Buy" button, a window with the purchase form appears ... etc. In fact, the window is one, the content in the window is different. Why create a separate window for each sneeze?
Made a window.
Made a button.
When the button is clicked, an Action is sent. A simple object designed to simply change the state. Passing a component to a state is a bad idea.
OK. I just write a string to the state ( 'Authorization' ). I read this line in the window container. I check if the string === 'Authorization' - I pass the Authorization component to the view component in the props. If you do not take into account that the implementation of this is somehow not very beautiful, it still does not work - the component is not rendered in the template.
It would be possible to throw the name into the view, make a check and substitute the corresponding component, but check something in the template, push the logic there .... this is completely sad.
How would it be correct to implement this? It is highly desirable that you do not import any components into the window component, as I have done now, but simply somehow forward the desired component, such as by clicking "create a standard window and insert the component that I will now transfer into it."

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Frozen Coder, 2017-03-07
@f-end

I didn’t really go into it, but briefly, in order to pass one component to another and draw it there, you should pass the component through a function and call it where you need to display it.
Where Parent is rendered

let component = () => ( <ComponentChild /> );
...
<Parent child={ component } />

Inside Parent in method
render(){
   return( 
      { this.props.child && this.props.child() }
   )
}

Something like this. Thus, you can determine which component will be drawn somewhere at the top of the tree in a smart component, and pass it down to stupid display components as props through the function-variable-parameter.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question