nekromenzer
nekromenzer

Reputation: 342

passing prop to state in react js

const [nav, setNav] = useState({
firstPage: "active",
});

I want to pass my prop as value to state firstpage how I do this in correct manner

const addNavi = (prop) => {

//want to pass prop in to my state value
}

Upvotes: 0

Views: 158

Answers (2)

AmerllicA
AmerllicA

Reputation: 32522

You can use destructuring assignment the props in the argument of the AddNavi component signature (in parenthesis) and then pass it in as the first argument in useState, which will set the initial state of nav:

import React, { useState } from 'react';

const AddNavi = ({ firstPage }) => {

  const [nav, setNav] = useState(firstPage);
}

Hint: ReactJS components MUST start with upper case characters like AddNav not addNav.

Upvotes: 3

Krina Soni
Krina Soni

Reputation: 930

I suppose you want to initialize the state with props value, you can pass this like below.

const [nav, setNav] = React.useState({...props.firstPage});

Upvotes: 2

Related Questions