how to pass an element from other components to a specific component in React.js


I have a component which called <Header> and another component <AboutMe>, I wanted to pick an element with an id from <AboutMe> and add an event listener onClick.
the thing is whenever i try to use getElementById it returns the element which I wanted but when I try to add the event listener…throws an error.


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} >

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.

        <MyComponent src={props.src} 

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={() => {
                }} >

Answered By – r Blue

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published