logo
down
shadow

how to pass props to a component via onClick event?


how to pass props to a component via onClick event?

By : WillLangas
Date : November 21 2020, 03:00 PM
will help you Something like this should work. The important concept is that you need to have a parent to both of your subcomponents passing data. In this case, Expenses is the parent. In the parent, you create a function, showItemDetails that you pass down to ExpenseList. That is your clickhandler, which is used to pass back up the index location of the data you want to render. That showItemDetails then uses this.setState to give ItemDetails's the props you want.
code :
import React, {Component} from 'react'

export default class Expenses extends Component {
  constructor(props) {
    super(props)
    this.state = {
      expenseItems: []
    }
  }

  showItemDetails(idx) {
    const {expenseItems} = this.props.expenses.expenseList[idx]
    this.setState({expenseItems})
  }

  render() {
    const createdDates = this.props.expenses.expenseList.map(({createdAt}) => {
      return createdAt
    })
    const expenseListProps = {
      showItemDetails: (idx) => this.showItemDetails(idx),
      createdDates
    }
    const itemDetailsProps = {expenseItems: this.state.expenseItems}
    return (
      <div>
        <ExpenseList {...expenseListProps}/>
        <ItemDetails {...itemDetailsProps}/>
      </div>
    )
  }
}

class ExpenseList extends Component{
  render() {
    const expenseList = this.props.createdDates.map((date, idx) => (
      <div key={idx}>
        <button onClick={() => this.props.showItemDetails(idx)}>
          {date}
        </button>
      </div>
    ))
    return (
      <div>
        {expenseList}
      </div>
    )
  }
}

class ItemDetails extends Component {
  render() {
    debugger;
    const items = this.props.expenseItems.map(({uid, date, desc, amount}) => (
      <div>
        {uid}
        {date}
        {desc}
        {amount}
      </div>
    ))
    return (
      <div>
        {items}
      </div>
    )
  }
}


Share : facebook icon twitter icon
React component props only changing after second onClick event

React component props only changing after second onClick event


By : Anjali Chawla
Date : March 29 2020, 07:55 AM
With these it helps setState is an asynchronous function, meaning the data is only updated after you have called the onChange callback function. Therefore the App Component still gets the old value of this.state.number.
Try calling the onChange function after the setState is finished by:
code :
number(e) {
    console.log('You\'ve pressed number ' + e.target.value);
    this.setState({
        number: e.target.value
    }, () => {
        this.props.onChange(this.state.number);
    })
}
Pass event handler as props to react-native custom component

Pass event handler as props to react-native custom component


By : fengshuo
Date : March 29 2020, 07:55 AM
I hope this helps you . I have a custom component called MyButton.js , try to change
Pass props to another component onclick of a button

Pass props to another component onclick of a button


By : RodrigoGon
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , In your case you need to deal with callbacks. Callback is a concept in react.
Declare an event handler function in orders.js which sets the orderId to the state when button clicked in orders.js component and pass down that event handler function to Order component as props and pass down orderId as a prop to OrderViewer component
code :
  constructor(props){
      super(props);
      this.state = {
           orderId: null
      }
  }
  handleViewOrder = orderId = {
      this.setState({
          orderId
      });
  }
  render(){
    return(<div>
     <div><Order 
       orderno='abc'
       title='abc'
      status='abc'
      entity='abc'
      po='abc'
      duedate='abc' handleViewOrder={this.handleViewOrder} /></div>
  </div>
  <div><OrderViewer orderId={this.state.orderId} /></div>)}
   <div>
      <button onClick={() => this.props.handleViewOrder(this.props.orderno)}>View Order</button>
      <p><span>{this.props.orderno}</span> 
     <span>{this.props.title}</span></p>
     <p>{this.props.entity} - {this.props.po}</p>
     <p>Due {this.props.duedate}</p>
 </div>
   <div>{this.props.orderId}</div>
  <button onClick={() => this.handleViewOrder(this.props.orderno)}>View Order</button>
   <button onClick={() => this.props.handleViewOrder(this.props.orderno)}>View Order</button>
            { Orders.map((order) => <Order 
                 orderno={order.orderno}
            title={order.title}
                 status={order.status}
                entity={order.entity}
                po={order.po}
            duedate={order.duedate}
            handleViewOrder={this.handleViewOrder}/> )}
            { Orders.map((order) => <Order 
            orderno={order.orderno}
            title={order.title}
            status={order.status}
                entity={order.entity}
            po={order.po}
                            key={order.orderno}
            duedate={order.duedate}
            handleViewOrder={this.handleViewOrder}/> )}
React: Pass function to child component as props, call onClick in child component

React: Pass function to child component as props, call onClick in child component


By : user3129781
Date : March 29 2020, 07:55 AM
it helps some times You need to pass handleOptionChange as a callback of handleOptionChange prop
Change this:
code :
handleOptionChange={() => this.handleOptionChange()}
handleOptionChange={this.handleOptionChange}
How to get the props with onClick and pass with component in redux?

How to get the props with onClick and pass with component in redux?


By : Eudjinn
Date : March 29 2020, 07:55 AM
I wish this help you Let's try to optimize your react-redux flow here so we can explain things a bit easier.
First let's try to make your App component look like this:
code :
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore, combineReducers } from "redux";
import articles from "./reducers/articles";
import Articles from "./components/Articles";
import Preview from "./components/Preview";

const store = createStore(
  combineReducers({
    articles: articles
  })
);

function App() {
  return (
    <Provider store={store}>
      <div className="App">
        <Articles />
        <Preview />
      </div>
    </Provider>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
const initialState = {
  articles: [
    {
      title: "Corgi",
      url: "https://www.akc.org/dog-breeds/cardigan-welsh-corgi/"
    },
    {
      title: "Leopard Dog",
      url: "https://www.akc.org/dog-breeds/catahoula-leopard-dog/"
    }
  ],
  article: {}
};

const articlesReducer = (state = initialState, action) => {
  switch (action.type) {
    case "SHOW_URL":
      return {
        ...state,
        article: action.payload
      };
    default:
      return state;
  }
};

export default articlesReducer;
export const showUrl = article => {
  return {
    type: "SHOW_URL",
    payload: article
  };
};
import React from "react";
import { connect } from "react-redux";
import Article from "./Article";

const Articles = ({ articles }) => {
  return (
    <div>
      {articles.articles.map(article => {
        return <Article article={article} />;
      })}
    </div>
  );
};

const mapStateToProps = state => {
  return {
    articles: state.articles
  };
};

export default connect(mapStateToProps)(Articles);
import React from "react";
import { connect } from "react-redux";
import { showUrl } from "../actions/articleActions";

const Article = ({ article, showUrl }) => {
  return (
    <div>
      <button onClick={() => showUrl(article)}>{article.title}</button>
    </div>
  );
};

const mapDispatchToProps = dispatch => {
  return {
    showUrl: article => {
      dispatch(showUrl(article));
    }
  };
};

export default connect(
  null,
  mapDispatchToProps
)(Article);
import React from "react";
import { connect } from "react-redux";

const Preview = ({ articles }) => {
  const thisArticle = articles.article;
  return (
    <div>
      <h4>{thisArticle.title}</h4>
      <a href={thisArticle.url}>Go To Link</a>
    </div>
  );
};

const mapStateToProps = state => {
  return {
    articles: state.articles
  };
};

export default connect(mapStateToProps)(Preview);
Related Posts Related Posts :
  • Where did react install `invariant` lib?
  • Redirecting with react-router in a react redux app
  • Unexpected token, expected , error (React-navigation)
  • react-redux project. Chrome dev tools does not show all projects files
  • How to cache API response and use it later in react & redux?
  • With Semantic UI React, how to set the width and height for Image Avatar?
  • reactjs, how to pass props at the class level
  • Passing default values to disabled input fields, but it is preventing input into enabled fields in Redux-Forms
  • eslint complaining about getInitialProps
  • Session Sharing react/express
  • Using API keys in a react app
  • How best to stop Link component from redirecting when a delete icon is clicked
  • React conditional style not rendering properly
  • How do I configure my Nginx server to work with a React app in a subfolder?
  • Is dangerouslySetInnerHTML the only way to render HTML from an API in React?
  • react-hot-loader not working properly with all urls
  • Reactjs onScroll event not responding
  • returning components following setState
  • Imports failing in React 16 tests with enzyme and jest
  • React-Redux: Mutating the state to emulate action side-effects with redux-undo
  • Interval API calls in Redux-Observable
  • How do we get props or states in navigationOptions?
  • Ideas for code refactoring typescript switch statement
  • How to change the height of textarea with content?
  • Set state objects directly and call setState
  • React app throwing error: Uncaught TypeError: Cannot read property 'shape' of undefined
  • Can't switch Tabs in TabNavigator (react-navigation)
  • Route authorization HOC cause to remount children 3-times
  • Google Maps With ReactJs
  • React Router 4: Programmatically change route but not rendering component
  • How to access static method when using connect & HoC?
  • Does React have keep-alive like Vue js?
  • How to export or preview page content `onClick` as pdf/xls in the browser in ReactJs?
  • Filter list on the fly by a parameter
  • mapStateToProps function , targeting id of the post instead of all the posts
  • How To Implement Google reCAPTCHA With Redux Form
  • Flow: How to type a HOC that accepts a prop the wrapped component doesn't care about
  • React Material-UI tabs with drawers
  • Why wont my vote reducer populate UI correctly
  • How can I allow access to specific React Hash Routes using Spring Security?
  • Is it OK to call an action creator directly rather than through mapStateToProps?
  • Multiple signalR connections
  • React handle state update
  • How to access array of objects subelement from redux reducers
  • Reactjs - How to use redux in Stripe checkout form
  • Change fetch to async syntax
  • Auto-generating a graphql schema for relay (Graphene server)
  • JSX description in Facebook and Typescript docs
  • react-native: how to modify the format in which data is stored in AsyncStorage?
  • why component is not rendered in parent layout in react JS using react routing?
  • Select with optgroup in ReactJS
  • Ant Design form set values form props
  • How to make a row responsive using bootstrap in a react-application?
  • How would I pass data from one page to another in react?
  • How to resolve ':react-native-vector-icons' error for a successful build?
  • React 16.6.3 Context API contextType not being set
  • react fetch data and render the error if any
  • Setting Relative Path in React Router
  • Jest: How to provide Redux mock store to only the child component?
  • How to solve selectOptions.some is not a function while using AsyncCreatableSelect?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org