How to share a property with other components in React?

1

Hello, I'm new to React and I have a question about sharing properties. For example, I want to have a parent component that will have a "visible" property, and I want to share it with all my child components, so I can use it this way, for example:

CustomInput visible="true";
CustomDropDown visible="false";

I would like to know the best way to do this, respecting good practices. Thanks for the help!

    
asked by anonymous 14.02.2017 / 02:04

1 answer

2

To pass values to descendants you must use props . To pass all props of a parent element to a descendant you can use {...this.props} in the props of the descending element.

Example:

class Pai extends React.Component {
	render() {
		return (
			<div>
			Eu sou uma "div". Visivel?: {this.props.visivel ? 'sim' : 'não'}
			<Filho {...this.props}/>
			</div>
		);
	}
}


class Filho extends React.Component {
	render() {
		return <p>Eu sou um "p". Visivel?: {this.props.visivel ? 'sim' : 'não'}</p>;
	}
}

ReactDOM.render(
	<Pai visivel={true}/>,
	document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
  <!-- This element's contents will be replaced with your component. -->
</div>
    
14.02.2017 / 09:49