Send State Props to Another Component in React with onClick



In this article we will learn about sending state/props from one component to another component in React.?

Before moving on, let's see what state and props are in React. We use props and state for dynamic content which get changed from time to time.

  • Props: Props are short form of Properties. These are read-only, meaning they can't be changed, and we pass props from the parent component to the child component. means the child component which has props received from the parent component can't be modified.
  • State: State is used to store data for a particular component and its mutable variable. in other words, we can change this within that component. If we change any state value, then it will immediately trigger a re-render of that particular component where it is being managed.


Syntax

Syntax for passing any value as a prop from parent to child.

const AnyParentComponent = () => {
  const value = "Hey there kalyan!";
  return (
    <div>
      <ChildComponent propName={propValue} />
    </div>
  );
};

Examples of Sending state/props to Another Component

Let's say we have ComponentA and ComponentB and we want to pass state as a prop which is a dummy text from ComponentA to ComponentB, below is the program that does this work.

Example 1

Passing state as a prop to other components.

ComponentA.jsx

import React, { useState } from "react";
import ComponentB from "./ComponentB";
const ComponentA = () => {
  const loremIpsum =
    "Lorem Ipsum is simply dummy text of the
     printing and typesetting industry. Lorem 
     Ipsum has been the industry's standard 
     dummy text ever since the 1500s, when an 
     unknown printer took a galley of type and 
     scrambled it to make a type specimen book.
     It has survived not only five centuries, 
     but also the leap into electronic typesetting,
     remaining essentially unchanged.";
  const [content, setContent] = useState("");
  const sendContent = (e) => {
    e.target.innerText = "Sent";
    setContent(loremIpsum);
  };
  return (
    <div>
      <button onClick={sendContent}> 
        Send Content to Component B
      </button>
      <ComponentB content={content} />
    </div>
  );
};

export default ComponentA;

ComponentB.jsx

import React, { useState } from "react";

const ComponentB = ({ content }) => {
  const [isOpen, setIsOpen] = useState(false);
  const toggleAccordion = () => {
    setIsOpen(!isOpen);
  };
  return (
    <div
      style={{
        border: "1px solid #ccc",
        borderRadius: "4px",
        width: "80%",
        margin: "20px auto",
      }}
    >
      <div
        onClick={toggleAccordion}
        style={{
          padding: "10px",
          backgroundColor: "#000",
          cursor: "pointer",
          fontWeight: "bold",
        }}
      >
        {isOpen ? "Click to Hide Content" : "Click to Show Content"}
      </div>
      <div
        style={{
          maxHeight: isOpen ? "100px" : "0",
          overflow: "hidden",
          overflowY: "auto",
          transition: "max-height 0.1s ease",
        }}
      >
        {isOpen ? (
          <p style={{ padding: "10px" }}>{content}</p>
        ) : (
          "No content to display."
        )}
      </div>
    </div>
  );
};
export default ComponentB;

Output

Explanation

ComponentA
  • We used the 'content' state to manage the loreamIpsum text.
  • When the button is clicked then it calls the sendContent function which updates the `content` state using its setContent function.
  • Then this updated content is passed to `ComponentB` as a prop.
  • Before clicking the button its passed prop as empty content as the content state has the initial value as '' empty string.
ComponentB
  • We used the 'content' state to manage the loreamIpsum text.
  • When the button is clicked then it calls the sendContent function which updates the `content` state using its setContent function.
  • Then this updated content is passed to `ComponentB` as a prop.
  • Before clicking the button it passes the prop as empty content as the content state has an initial value as '' empty string.

Example 2

Passing state as a prop to other components.

ComponentA.jsx
import React, { useState } from "react";
import ComponentB from "./ComponentB";
const ComponentA = () => {
  const [message, setMessage] = useState("No Message");
  const updateMessage = () => {
    setMessage("Hey there Kalyan ?????");
  };
  return (
    <div>
      <button onClick={updateMessage}>Send Message</button>
      <ComponentB message={message} />
    </div>
  );
};

export default ComponentA;
ComponentB.jsx
import React from "react";
const ComponentB = ({ message }) => {
  return (
    <div>
      <h2>Message from prop: {message}</h2>
    </div>
  );
};
export default ComponentB;

Output

Explanation

In ComponentA we have the state as `message` and clicking the Send Message button will call the `updateMessage` function and it will update the message state as some text. This state is being passed as a prop into CompoentB from componentA. in ComponentB we are simply receiving the prop as a message and printing it.

Conclusion

So, we get to know how state and props are passed between different components in react. Props are read-only and we pass them from the upper component to the lower child component it is immutable while the state is mutable and used within that same component.

Updated on: 2024-08-19T12:38:09+05:30

130 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements