Related to your title of this question:
You can achieve the passing of data and objects through to child components through the use of attributes where you use your component.
You really don’t need to use the DOM to access the elements on the page, and with React being highly dynamic in nature, the DOM is in a constant state of change which can lead to many issues if you try to bypass React.
So if you have your header component used in your app like this…
<PageHeader userData={ userData } />
Then within your component, which is named PageHeader in this example, define the constants as:
const PageHeader = (props) => {
const userData= props.userData;
Note the object name to use with “props” is the same that you used with the attribute name.
Props will contain all attributes that are defined on the attribute where the component is used.
Just to provide another way to use “props” (the name is not significant) I’ll include this code snippet too. Notice that react will auto map each one to it’s proper constant… which is pretty cool.
const PageHeader = ( props ) => {
const { uischema, schema, path, visible, renderers, userData } = props;
And one last thing that I should mention, is the use of the props.children
, which can be very useful too. This is where DivScrollable is defined, and is using the props.children
.
const DivScrollable = (props) => {
return (
<div className={styles.divscrollable} >
{props.children}
</div>
);
};
So the power of props.children
is that it passes along the contents of what is contained between the opening and closing tags of a component. In this example it’s the MyComponent
object that is within the props.children
object. But it could also include others too since it’s “all of the content” between the component tags.
<DivScrollable>
<MyComponent src={props.src}
theme="monotyped"
spacing="4"
enableClipboard="true"
name={null}
/>
</DivScrollable>
To then address the onClick
handling, which you mention within the body of your question, you can use use it like the following, where I am reusing the above examples… see the “onClick” addition within the DivScrollable component.
const DivScrollable = (props) => {
const performSomeFunction= (aValue) => {
... code goes here...;
};
return (
<div className={styles.divscrollable}
onClick={() => {
performSomeFunction(true);
}} >
{props.children}
</div>
);
};
1
solved how to pass an element from other components to a specific component in React.js [closed]