I'm trying to find the proper way to define some components which could be used in a generic way:
value="2">
There is a logic going on for rendering between parent and children components of course, you can imagine and as an example of this logic.This is a dummy implementation for the purpose of the question:var Parent = React.createClass({ doSomething: function(value) { }, render: function() { return ({this.props.children}); }});var Child = React.createClass({ onClick: function() { this.props.doSomething(this.props.value); // doSomething is undefined }, render: function() { return ( onClick={this.onClick}>); }});The question is whenever you use {this.props.children} to define a wrapper component, how do you pass down some property to all its children? Answer Cloning children with new propsYou can use href="https://reactjs.org/docs/react-api.html#reactchildren" rel="noreferrer">React.Children to iterate over the children, and then clone each element with new props (shallow merged) using href="https://reactjs.org/docs/react-api.html#cloneelement" rel="noreferrer">React.cloneElement e.g:const Child = ({ doSomething, value }) => ( doSomething(value)}>Click Me);class Parent extends React.PureComponent { doSomething = value => { console.log('doSomething called by child with value:', value); } render() { const childrenWithProps = React.Children.map(this.props.children, child => React.cloneElement(child, { doSomething: this.doSomething }) ); return {childrenWithProps} }};ReactDOM.render( value="2" /> , document.getElementById('container'));Fiddle: rel="noreferrer">https://jsfiddle.net/2q294y43/2/Calling children as a functionYou can also pass props to children with rel="noreferrer">render props. In this approach the children (which can be children or any other prop name) is a function which can accept any arguments you want to pass and returns the children:const Child = ({ doSomething, value }) => ( doSomething(value)}>Click Me);class Parent extends React.PureComponent { doSomething = value => { console.log('doSomething called by child with value:', value); } render() { return {this.props.children(this.doSomething)} }};ReactDOM.render( {doSomething => ( /> )} , document.getElementById('container'));Instead of or simply <> you can also return an array if you prefer.Fiddle: href="https://jsfiddle.net/ferahl/y5pcua68/7/" rel="noreferrer">https://jsfiddle.net/ferahl/y5pcua68/7/ - December 29, 2017 Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest No comments: Post a Comment Newer Post Older Post Home Subscribe to: Post Comments (Atom) php - file_get_contents shows unexpected output while reading a file I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ... .image { width: 100%; } database - Android Studio: show username in textview with SQLite I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th... regex - Splitting string and removing whitespace Python I would like to split a String by comma ',' and remove whitespace from the beginning and end of each split. For example, if I have ... How to solve the java.lang.ArrayIndexOutOfBoundsException: 1 >= 0 error in my java program? I got an error in my Java program. I think this happens because of the constructor is not intialized properly. My Base class Program public ... Search This Blog
and as an example of this logic.This is a dummy implementation for the purpose of the question:var Parent = React.createClass({ doSomething: function(value) { }, render: function() { return ({this.props.children}); }});var Child = React.createClass({ onClick: function() { this.props.doSomething(this.props.value); // doSomething is undefined }, render: function() { return ( onClick={this.onClick}>); }});The question is whenever you use {this.props.children} to define a wrapper component, how do you pass down some property to all its children? Answer Cloning children with new propsYou can use href="https://reactjs.org/docs/react-api.html#reactchildren" rel="noreferrer">React.Children to iterate over the children, and then clone each element with new props (shallow merged) using href="https://reactjs.org/docs/react-api.html#cloneelement" rel="noreferrer">React.cloneElement e.g:const Child = ({ doSomething, value }) => ( doSomething(value)}>Click Me);class Parent extends React.PureComponent { doSomething = value => { console.log('doSomething called by child with value:', value); } render() { const childrenWithProps = React.Children.map(this.props.children, child => React.cloneElement(child, { doSomething: this.doSomething }) ); return {childrenWithProps} }};ReactDOM.render( value="2" /> , document.getElementById('container'));Fiddle: rel="noreferrer">https://jsfiddle.net/2q294y43/2/Calling children as a functionYou can also pass props to children with rel="noreferrer">render props. In this approach the children (which can be children or any other prop name) is a function which can accept any arguments you want to pass and returns the children:const Child = ({ doSomething, value }) => ( doSomething(value)}>Click Me);class Parent extends React.PureComponent { doSomething = value => { console.log('doSomething called by child with value:', value); } render() { return {this.props.children(this.doSomething)} }};ReactDOM.render( {doSomething => ( /> )} , document.getElementById('container'));Instead of or simply <> you can also return an array if you prefer.Fiddle: href="https://jsfiddle.net/ferahl/y5pcua68/7/" rel="noreferrer">https://jsfiddle.net/ferahl/y5pcua68/7/ - December 29, 2017 Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest No comments: Post a Comment Newer Post Older Post Home Subscribe to: Post Comments (Atom) php - file_get_contents shows unexpected output while reading a file I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ... .image { width: 100%; } database - Android Studio: show username in textview with SQLite I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th... regex - Splitting string and removing whitespace Python I would like to split a String by comma ',' and remove whitespace from the beginning and end of each split. For example, if I have ... How to solve the java.lang.ArrayIndexOutOfBoundsException: 1 >= 0 error in my java program? I got an error in my Java program. I think this happens because of the constructor is not intialized properly. My Base class Program public ... Search This Blog
Blog Archive ► 2020 (79) ► January 2020 (79) ► 2019 (5283) ► December 2019 (475) ► November 2019 (449) ► October 2019 (447) ► September 2019 (466) ► August 2019 (486) ► July 2019 (423) ► June 2019 (418) ► May 2019 (439) ► April 2019 (431) ► March 2019 (433) ► February 2019 (394) ► January 2019 (422) ► 2018 (3641) ► December 2018 (463) ► November 2018 (416) ► October 2018 (456) ► September 2018 (463) ► August 2018 (447) ► July 2018 (442) ► June 2018 (420) ► May 2018 (227) ► January 2018 (307) ▼ 2017 (1271) ▼ December 2017 (487) r - How can two strings be concatenated? c - What is the difference between a definition an... c# - Does a web.config substitute app.config? How do I display an alert dialog on Android? java - Parsing from String to Date throws Unparsab... c - UNUSED macro warning kwargs reserved word in python. What does it mean? Movie where jury gets swapped just before a trial ... loops - Javascript Break Statement Goodness CSS multiple selectors without comma c# - Why is there huge performance hit in 2048x204... python - Python3 - Generate string matching multip... javascript - In what situation we must use localst... java - ArrayList.add throws ArrayIndexOutOfBoundsE... html - jQuery click function doesn't work after aj... Python : write text to file line by line javascript - state provider and route provider in ... Undefined index in PHP analysis - Were parts of The Dark Knight Rises a c... How can I make SQL case sensitive string compariso... c++ - Is memory barrier or atomic operation requir... java - Why is try/catch needed in some cases but n... bash - How to use double or single brackets, paren... deeper understanding of closure in Javascript templates - declaring a C++ set iterator html - Find JavaScript handler connected to a butt... python - cannot import a module after os.chdir() r - How to persist changes in a text file using sh... php - static::staticFunctionName() css3 - CSS select first element with a certain class email - Error sending special characters on mail f... 'citizen-kane' tag wiki - Movies & TV design patterns - What are MVP and MVC and what is... javascript - How to pass props to {this.props.chil... sql server - What do Clustered and Non clustered i... how to select last autoincrement id using php and ... php - How to turn off magic quotes on shared hosting? javascript - Why can't I pass "window.location.rel... sql server - How can I use single quote inside sql... javascript - Pushing an object to beginning of an ... kernel - program context from perf sample event sql server - T-SQL: Combine rows to one row c++ - How to read line by line or a whole text fil... pandas - Python still having issues with try-excep... c++ - What is a smart pointer and when should I us... python - How to install python3 version of package... security - Exploitable Java functions Android Java.Lang.RuntimeException : Unable to sta... javascript - Round to at most 2 decimal places (on... Is __init__.py not required for packages in Python... python - Getting the last element of a list marvel cinematic universe - Which related films do... c - Function Pointer cast at declaration c++ - Namespace + functions versus static methods ... Generating random whole numbers in JavaScript in a... c - Is volatile needed when variable is only read ... html - Click event not working on objects added dy... html - CSS - design parent class if child has a sp... javascript - Is this the right code to achieve for... reactjs - How to push to History in React Router v4? shell - Cannot attach file and include a body whil... performance - Why is zipped faster than zip in Scala? plot explanation - Why was the surgery pod configu... excel - Copy range of cells (excluding blanks) int... javascript - How to bind function on different but... c - Why does MSVS not optimize away +0? javascript - html5 localStorage error with Safari:... r - Label points in geom_point c# - Why does DirectoryServicesCOMException occur ... php - Parse error: syntax error, unexpected T_BOOL... javascript - Using a Button instead of href php - SQL injection that gets around mysql_real_es... c++ - What are the basic rules and idioms for oper... Android simple alert dialog 'true-blood' tag wiki c# - group inside a list of objects and modify Change date format in a Java string character - How old is Ross Geller? - Movies & TV props - Are fictional trademarks or brand names us... java - How to fix 'android.os.NetworkOnMainThreadE... c++ - Why is "using namespace std;" considered bad... bash - When do we need curly braces around shell v... inheritance - How do you declare an interface in C++? jvm - what is difference between Java Method And N... php - original variable name passed to function? javascript - state provider and route provider in ... java - JPanel not showing up on JFrame plot explanation - Why does Blake ask the salesmen... alphanumeric - Generating unique, random alpha num... utf 8 - php encoding of posted data changed php - Multiple matches within a regex group? python - Large, persistent DataFrame in pandas character - Is Bane just an agent in Talia's plan,... arguments - Reference — What does this symbol mean... Pointers in C: when to use the ampersand and the a... How to solve a PHP error in Laravel without changi... yaml - How to break up command in CircleCI yml to ... android - Google Maps gets crash between two activity unicode - Remove multiple BOMs from a file php - PDO prepared statements to store html content ► November 2017 (432) ► October 2017 (352)