I have passed two props in two separate renders of the same component and passed one prop as a function and other as a string. However on accessing it in the component for rendering, it says: "props.prop1 is not a function"
This my App.js file:
import React from 'react';
import Test from './components/Test';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<Test prop1={() => {return "a"}}/>
<Test prop2="b"/>
</header>
</div>
);
}
export default App;
This my Test.js file:
import React from "react";
function Test(props) {
return (
<>
<div className="test">
<div>Test data {props.prop1()} </div>
<div>{props.prop2}</div>
</div>
</>
);
}
export default Test;
You have declared 2 <Test> components in your <App> and you are not passing prop2 on the 2nd one:
You might want to pass them all at the same time like so:
import React from 'react';
import Test from './components/test';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit
{' '}
<code> src / App.js </code>
{' '}
and save to reload.
</p>
<Test
prop1={() => 'a'}
prop2="b"
/>
</header>
</div>
);
}
export default App;
You are passing prop1 and prop2 alternatively. So you should pass both props.
If you want to pass props alternative then you can do as. Add default function(Which just invoke but won't do anything) if prop1 is absent as
prop1 = () => {}
1) Should use when you want to show the div despite of prop1 value
import React from "react";
function Test({ prop1 = () => {}, prop2 }) {
return (
<>
<div className="test">
<div>Test data {prop1()} </div>
<div>{prop2}</div>
</div>
</>
);
}
export default Test;
2) If you want to hide the div if the prop1 is not present then you can use && as
import React from "react";
function Test(props) {
return (
<>
<div className="test">
{
props.prop1 && <div>Test data {props.prop1()} </div>
}
{
props.prop2 && <div>{props.prop2}</div>
}
</div>
</>
);
}
export default Test;