DEV Community

adriangheo
adriangheo

Posted on • Edited on

01.01 Pass props to component (functional components)

App preview:

The way the app will look like


Initial setup:

npx create-react-app actual-props-example
cd actual-props-example
rm src/App.test.js src/index.css src/logo.svg src/reportWebVitals.js src/setupTests.js 
mkdir src/components
cd ./src/components 
touch ./ParentComponent.jsx ./ParentComponent.css ./ChildComponent.jsx ./ChildComponent.css 
Enter fullscreen mode Exit fullscreen mode

Project files:

An image of project file structure


src/index.js:

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <App />
);
Enter fullscreen mode Exit fullscreen mode

src/App.js:

import React from 'react';
import CustomComponent from './components/CustomComponent';
import './App.css'

function App() {
  return (
    <div className="app">
      <h2>App.js</h2>
      <CustomComponent  
        title="This string is passed through props from App.js"
      />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

src/App.css:

.app{
    background-color: lightskyblue;
    padding: 20px 10px;
}
Enter fullscreen mode Exit fullscreen mode

src/components/CustomComponent.jsx:

import React from 'react'
import './CustomComponent.css'

function CustomComponent(props) {
  return (
    <div className='custom-component'>
        <h3>CustomComponent.jsx </h3>
        <p> {props.title}</p>
    </div>
  )
}

export default CustomComponent
Enter fullscreen mode Exit fullscreen mode

src/components/CustomComponent.css:

.custom-component{
    background-color: lightsalmon;
    padding: 10px 10px;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)