Reputation: 35
I'm trying to pass a function as a parameter for a component, however it does not see the function I pass in as a function.
Here's the page (I'm only going to provide what's imoprtant)
const Home = () => {
const nav = useNavigate()
const [userList, setUserList] = useState([]);
const [loggedInUser, setLoggedInUser] = useState({});
const [currentChat, setCurrentChat] = useState(undefined);
const [showMenu, setShowMenu] = useState(false);
let navMenu
const handleChatChange = (chat) => {
setCurrentChat(chat);
}
return (
<div id='sidebar'>
<div>
<Userlist users={userList} switchChat={handleChatChange}/>
</div>
</div>
)
Here is the react component that provides the error
const Userlist = ( props, switchChat ) => {
const switchCurrentchat = (user) => {
switchChat(user);
}
return (
<div>
<div id='home-header'>
<h1>DevsHelp</h1>
</div>
<div id='userlist'>
{props.users.map((user) => {
return (
<div key={user._id} className='user' onClick={() => switchCurrentchat(user)} >
<h3>{user.username}</h3>
</div>
)
})}
</div>
</div>
)}
Whenever switchChat is called upon, it returns an error stating "switchChat" is not a function.
If I do a console.log(user) instead of switchChat(user), it logs the user, so the function works, however it's just not reading it as a function.
If anyone could help me, I would appreciate it a lot, thanks!
Upvotes: 0
Views: 81
Reputation: 641
React components receive one object, commonly referred to as props.
If you wrap the params in curly braces, you can refer to them by name inside the component. Like this:
const Userlist = ({ users, switchChat }) => {
If you do this, you would need to refer to users directly inside the component. So no props.users
anymore.
You can also just refer to them via the props object:
const Userlist = (props) => {
// props.users and props.switchChat are available here
}
Upvotes: 1