Sign in
Log inSign up

Reactjs: How to set the state of another component?

jim toby's photo
jim toby
·Nov 5, 2018

I have created this sandbox code. What I am trying to do is render a text label based off of user action from a different component. I am using react router so I would like to direct to a different url when users click a button. So the first component users see is two buttons titled "Add Product" and "Manage Product". Here is the code of my Button.js:

import React from "react";
import { Button, AppProvider } from "@shopify/polaris";
import { withRouter } from "react-router-dom";
class App extends React.Component {
  handleClick = () => {
    //set the state of Result.js
    this.props.history.push("/result");
  };

  render() {
    return (
      <div>
        <AppProvider>
          <Button onClick={this.handleClick}>Add product</Button>
        </AppProvider>
        <AppProvider>
          <Button onClick={this.handleClick}>Manage Product</Button>
        </AppProvider>
      </div>
    );
  }
}

export default withRouter(App);

And then in my result.js which is the component users will be directed to, I want to display the title of the button they chose, so either "Add Product" or "Manage Product". Here is my result.js that simply displays "Hello World!" for now:

import React from "react";

export default class Result extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      label: "Hello World!"
    };
  }

  render() {
    return <p> {this.state.label}</p>;
  }
}

Essentially, I want to change the state of my Result component based on user action in my App component. Can anyone help me with this? Or is it wrong to change the state of a component with a different url, meaning I should do conditional rendering within the same component?

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct