React is a JavaScript library developed by the engineers at Facebook. It is used for building user interfaces for web applications and allows developers to build reusable components inside their applications for easy management and overall code structuring.
Now that we have an understanding of what React is, let's take a look at the different methods that are used for passing values inside attributes.
Static Values
Dynamic Values
If we want to pass fixed values to variables, we will pass them as static values. We will enclose the variables in curly braces {}
as all code inside curly braces is executed as JavaScript code.
First, we will create a React component to return the value inside the variable.
Next, we will declare the variables we want to pass and initialize them.
After initializing variables, we will return their values by enclosing them in curly braces.
Below we see a sample application that illustrates how this method is used.
Below is a brief explanation of the code:
Lines 5–6: We create two static variables.
Lines 9–16: Variables are then returned to the webpage.
Lines 11 and 14: We can see how our variables are enclosed in curly braces to be passed.
We may also need to update the data dynamically, such as upon a user's provided input. This can be done with the use of a useState hook. This hook is used for storing and passing dynamic data to components.
Below are the steps we must follow to pass values using the useState hook:
First, we will create a react component to pass the hooks data.
Next, we will create a state hook inside the component function. The syntax is shown below, the stateVariable
holds the data of the state hook, the setState
function allows us to update the data in the stateVariable
, and the initialValue
is the data we store in the stateVaraible
on hook creation.
const [stateVariable, setState] = useState(initialValue);
We will then create a function that will use the hook's setState
function to update the value of the stateVariable
.
In the return statement, we will pass the data inside the hook using the stateVariable
and bind the update function to a button, when pressed it would change the value of the stateVariable
.
Below is a sample application that further explains the steps mentioned above.
Below we can see a brief explanation of the code:
Line 5: We create a state hook and set its initial value to "Educative".
Lines 8–15: We create and define a function that updates the value inside the state variable.
Line 19: We are returning a component named TitleName, in which we are passing the state variable.
Line 21: We provide a button that, when clicked, calls the update function and updates the value of the state variable to "Educative.io".
Lines 27–29: We define the TitleName component that represents a child component. It takes a text variable as an argument and sends it to the parent as an h1 tag.
Free Resources