1

this really sound like a simple thing to know but I couldn't find any articles/resources so asking here.

how can I create components like Form.Input, Form.Select and use as follows -

import Form from '../Form';
...
const MyComponent = (props) => {
  ...
  return (
    <Form>
      <Form.Input />
      <Form.Select />
    </Form>
  );
}

So I basically want to understand what Form component is like that it is behaving like an object with sub exports like Input as Form.Input and Form.Select.

I've seen such codes at some places. Also we use React.Component, don't we? I only know to export default and named components so I can create different exports like Input and Select but can't figure out how exporting Form.Input could work ?

Gaurav
  • 1,668
  • 1
  • 13
  • 30

3 Answers3

1

The dot notation may make this seem like a subcomponent, but it is just another component attached to the Form component. Take a look at the codesandbox example

Basically, you have a component Form:

export const Form = (props) => {
  const Item = ({ children }) => <p> {children} </p>;
  Form.Item = Item;
  return <div>{props.children}</div>;
};

And you can access this like:

import "./styles.css";
import { Form } from "./Form";
export default function App() {
  return (
    <Form>
      <Form.Item> Test </Form.Item>
      <Form.Item> Test 2 </Form.Item>
    </Form>
  );
}
Sinan Yaman
  • 5,714
  • 2
  • 15
  • 35
1

You can add them to your Form component before exporting :

import React from 'react';

const Form = ({ Input, Select, children }) => (
...
);

const Input = ({ children }) => children;
Form.Input = Input;

const Select = ({ children }) => children;
Card.Select = Select;

export default Form;

More info here if you want : https://dev.to/shayanypn/buckle-with-react-sub-component-10ll

achilleb
  • 169
  • 10
0

On file Form.js

export default {
  Input,
  Select,
}

const Input = (props) => {
  // xyz
}

const Select = (props) => {
  // xyz
}
italant
  • 187
  • 1
  • 12