简体   繁体   中英

React JS pass the data or child component to parent component

Is it possible to pass the data from the child component to the parent component using props?

-Parent component
  --- ItemList component.
  --- DisplatSelect component from the itemList component

I have a list of item in the child component which came from to the parent component, then I want to send the index of the selected data to the other child component located in the parent component.

Can't example well, kindly see the attached screenshot for other references. Thanks a lot!

enter image description here

You can keep the data in the Parent component and use a function to pass the props from the child to the Parent. This concept is called Lifting State Up where you define the state at the highest common ancestor so all the child components are using the same data which in this case is the selecetd item

function Parent() {
  const [selectedItem, setSelectedItem] = useState(null);
  const data = []; // Your Data
  return (
    <>
      <h1>Your selected Item = {selectedItem}</h1>
      {data.map((item) => {
        <Child item={item} setSelectedItem={setSelectedItem} />;
      })}
    </>
  );
}

function Child({ item, setSelectedItem }) {
  return <Button onClick={() => setSelectedItem(item.id)}> {item} </Button>;
}



The simplest way, I think, is for the child component where the selection is made to accept a function properly, something like onSelectionChanged . If you had a button for each item passed to the child you could do something like:

Child Component A

const ChildA = ({ items, onSelectionChanged }) => {
    return (
        <div>
            {items.map((item, index) => (
                <button onClick={() => onSelectionChanged(index)}>Item</button>
            ))}
        </div>
    )
}

Child Component B

const ChildB = ({ selectedItem }) => {
    return (
        <div>
            Selected {selectedItem}
        </div>
    )
}

Parent Component

const Parent = () => {
    const [selection, sets election] = useState({});

    const onSelectionChanged = index => {
        console.log(`ChildA selection changed: ${index}`);
    }

    return (
        <div>
            <ChildA items={items} onSelectionChanged={onSelectionChanged} />
            <ChildB selectedItem={selection} />
        </div>
    )
}

So when your child component handles a change in the selection, it invokes the function passed as a prop onSelectionChanged . You can pass whatever data you want from ChildA to that function.

Note that the parent Component keeps the selected value (from ChildA) in local state, then passes that value to ChildB via a prop.

You can have a state variable in the parent component and pass it to child components to share data between them. I'll post a sample code block on how you can do this for your case.

export default function ParentComponent (props) {
  const data = ['image_1_url', 'image_2_url', ...] // Data for the images
  const [selectedIndex, setSelectedIndex] = useState(-1); // Selected index (-1 represents no selection)
  return (
    <ImageList data={data} selectImage={setSelectedIndex} />
    {(selectedIndex !== -1) ? (<SelectedImage data={data[selectedIndex]} />) : (<No ImageSelected/>)}
  );
}

And the image list component can then use the selectImage prop to select the image

export default function ImageList (props) {
  return (
    <div>
      props.data.map((imageUrl, index) => (
        <div onClick={() => {props.setSelected(index)}}>
          <img src={imageUrl}/>
        </div>
      ))
    </div>
  );
}

Yes it's possible. We have one parent state value and update every on click child component to the component.

import React, { useState } from "react";

const Child1 = (props) => {
  return (
    props.items.map( (item, index) => (
      <button key={index.toString()} onClick={() => { props.updateIndex(item.id) }}>
        {item.name}
      </button>
    ) )
  )
} 

const Child2 = (props) => {
  return (
    <h1>Item selected: {props.selectItem}</h1>
  )
} 

const ParentComponent = () => {
  const listItems = [
    {
      id:1,
      name: "sample name 1"
    },
    {
      id:2,
      name: "sample name 2"
    }
  ]
  const [selectItem, setSelectItem] = useState('None');
  return (
    <>
      <Child1 items={listItems} updateIndex={setSelectItem}/>
      <Child2 selectItem={selectItem}/>
    </>
  )
} 

export default function App() {
  return (
    <div className="App">
      <ParentComponent/>
    </div>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM