skip to Main Content

We use a modular approach with config files for our react project. So it goes like this:
Component which draws input fields ->
config file which has a parent div and has imported fields file in it ->
fields file which has fields with their IDs, values, etc.

So the question is, how can I select a particular child from the parent div and give it for example col-span-n?

I want it to look something like this:
grid grid-cols-1 gap-6 md:grid-cols-3 xl:grid-cols-8 mb-6 (and here classnames that will change particular child)

2

Answers


  1. If I understand correctly, you want to apply specific styling or classes to individual children within a parent div based on a modular configuration approach in your React project. One way to achieve this is by passing additional props to the child components and using those props to conditionally apply styles or classes.

    Here’s a simplified example to illustrate the concept:

    Component:

    // Parent component
    import React from 'react';
    import ChildComponent from './ChildComponent';
    import config from './config';
    
    const ParentComponent = () => {
      return (
        <div className="grid grid-cols-1 gap-6 md:grid-cols-3 xl:grid-cols-8 mb-6">
          {config.map((childConfig, index) => (
            <ChildComponent key={index} colSpan={childConfig.colSpan} />
          ))}
        </div>
      );
    };
    
    export default ParentComponent;
    

    Config:

    // Config file
    const config = [
      { colSpan: 'col-span-2' },
      { colSpan: 'col-span-1' },
      { colSpan: 'col-span-3' },
      // Add more configurations as needed
    ];
    
    export default config;
    

    ChildComponent:

    // Child component
    import React from 'react';
    
    const ChildComponent = ({ colSpan }) => {
      return <div className={`child ${colSpan}`}>Child Content</div>;
    };
    
    export default ChildComponent;
    

    In this example, the ParentComponent maps over the configuration array and passes the colSpan value to each ChildComponent. The ChildComponent then uses this prop to dynamically set the class for the specific child.

    You can customize the configuration based on your specific needs, and this approach allows you to maintain a modular and configurable structure for your React components while still providing flexibility in styling each child independently.

    Login or Signup to reply.
  2. You can try this way:

        const ParentComponent = () => {
          return (
            <div className="grid grid-cols-1 gap-6 md:grid-cols-3 xl:grid-cols-8 mb-6">
              {config.map((childConfig, index) => (
               <div key={index} className="col-span-1 md:col-span-2 lg:col-span-3">
                  <ChildComponent   />
               </div>
               
              ))}
            </div>
          );
        };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search