skip to Main Content

I’m starting learning about reactjs. But when i watch tutorial on youtube i often see that when definite component in sperate file and export, people always name the file name with component name defining in the file is similar.
For example:I see that to define a component name Book the video always names the file of Book component is** Book.js**
And i wonder that this is official rule of reactjs or may be convention of Reactjs community.

Can i name the file name and component in the file is difference?

2

Answers


  1. React doesn’t care about your filenames at all (and in fact, if you use a bundler, it’s going to combine source files into a small number of scripts for distribution). You can put one component in each file, or all of your components in a single file, and either way, it makes no difference to React. Components are just functions (either function components using hooks, or constructor functions for class components). Organize them as you see fit.

    Here’s an example with three components in the same script tag (loosely, "file"):

    const { useState, useEffect } = React;
    
    const Ticker = ({start}) => {
        const [value, setValue] = useState(start);
    
        useEffect(() => {
            setValue(start);
        }, [start]);
        
        useEffect(() => {
            const timer = setInterval(() => {
                setValue((v) => v + 1);
            }, 1000);
            return () => {
                clearInterval(timer);
            }
        }, []);
        
        return <span className="counter">{value}</span>;
    };
    
    const Strong = ({children}) => <strong>{children}</strong>;
    
    const Example = () => {
        return (
            <div>
                <Strong>Testing: <Ticker start={1} /></Strong>
            </div>
        );
    };
    
    const root = ReactDOM.createRoot(document.getElementById("root"));
    root.render(<Example />);
    <div id="root"></div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
    Login or Signup to reply.
  2. These rules are generally accepted by developers. Even the eslint rules will show an error. But the react will work with other names as well

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search