Search code examples
reactjsdrag-and-drop

How to pass each component id


I want to implement dragging components (beautiful dnd) so that the user can swap them. But for this, each component must have an id, as I understand it. But I do not know how to do it

import React from 'react';
import CardWeather from '../cardWeather/CardWeather';
import WeatherMap from '../cardWeatherMap/WeatherMap';
import Forecast from '../forecast/Forecast';
import WeatherGrapth from '../weatherGraph/WeatherGraph';
import './main.scss';
import { Droppable } from 'react-beautiful-dnd';

const Main = () => {

    return (
      <>
      <Droppable droppableId="main">
        {
          (provided) => (
            <div className="main-container"
            ref={provided.innerRef} 
            {...provided.droppableProps}
            >
            <CardWeather />
            <Forecast/>
            <WeatherGrapth/>
            <WeatherMap/>
        </div>
          )
        }

      </Droppable>


        <div className="pr">weather app</div>
        </>
    )
}

export default Main;


Solution

  • If I get this correctly you need to have some kind of id for every component in your case:

     <CardWeather />
     <Forecast/>
     <WeatherGrapth/>
     <WeatherMap/>
    

    You can pass the id by props for each component. Example:

    Main component:

      <CardWeather id="1" />
    

    CardWeather component:

    function CardWeather(props){
      const id = props.id
      ...
      return(
        <div data-id={id}>
        ...
        </div>
      )
    }
    ...
    

    And you have to do that for every component you want to drag and drop.