How do I share a property with other components in React?

Asked

Viewed 115 times

1

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

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

I would like to know how best to do this, while respecting good practice. I appreciate the help!

1 answer

2


To pass values to descendants you must use props. To pass all the props of a parent element to a descendant you can use {...this.props} in the props of the discriminating 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>
<script src="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>

  • Thank you very much Sergio, it worked perfectly!!!

  • @Felipeoliveira!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.