How do I set props to a JSX component I passed in as a prop?
Taken from https://reactjs.org/docs/composition-vs-inheritance.html shows how they do passing in a component as prop as per https://stackoverflow.com/a/63261751/242042
function SplitPane(props) {
return (
<div className="SplitPane">
<div className="SplitPane-left">
{props.left}
</div>
<div className="SplitPane-right">
{props.right}
</div>
</div>
);
}
function App() {
return (
<SplitPane
left={
<Contacts />
}
right={
<Chat />
}
/>
);
}
However, I want to modify the prop that was passed in. In the React-Native context, I would want to add additional styles to a component that was passed in as a prop.
Basically, you need to pass a function as props instead of JSX. Here is a sample code
//App.js
import React from "react";
import "./App.css";
import SplitPane from "./SplitPane";
import Contacts from "./Contacts";
import Chat from "./Chat";
function App() {
const ModifiedContact = (style) => <Contacts style={style} />;
const ModifiedChat = (style) => <Chat style={style} />;
return (
<div>
<SplitPane left={ModifiedContact} right={ModifiedChat} />
</div>
);
}
export default App;
//Chat.js
import React from "react";
const Chat =(props)=> {
return (
<div className={props.style}>
Hi Im chat
</div>
)
}
export default Chat;
//Contacts.js
import React from "react";
const Contacts =(props)=> {
return (
<div className={props.style}>
Hi Im contacts
</div>
)
}
export default Contacts;
//SplitPane.js
import React from "react";
const SplitPane = (props)=> {
const contactsStyle = "new-Class";
const chatStyle = "chat-Style";
return (
<div className="SplitPane">
<div className="SplitPane-left">
{props.left(contactsStyle)}
</div>
<div className="SplitPane-right" >
{props.right(chatStyle)}
</div>
</div>
);
}
export default SplitPane;
//App.css
.chat-Style {
color: rgb(10, 10, 10);
background-color: rgb(207, 27, 27);
text-align: center;
}
.new-Class {
color: #fff;
background-color: #888;
text-align: center;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With