0

I am trying to pass a function between two components but even though I do not have any errors, the function that I am passing wont show or to be precise it is not working. I have two files and one of them is creating a context while the other is using it (obviously). Now, they are not shown in App.js (which is rendered in index.js, usual stuff) they are in the seperate folder. I am using React Router to show one the pages (News.js).

Here are the files:

NewsContext.js

import React, { useContext, createContext, useState, useEffect } from "react";

export const newsK = React.createContext();

export const NewsContext = (props) => {

  const working = () => {
    console.log("it is working");
  };

  return <newsK.Provider value={working}>{props.children}</newsK.Provider>;
};

export default NewsContext;

News.js

import React, { useContext, useState, useEffect } from "react";
import { newsK } from "./NewsContext";
import { NewsContext } from "./NewsContext";


const News = () => {
  const data = useContext(newsK);
  return (
    <NewsContext>
      <div>
        <button onClick={data}></button>
      </div>
    </NewsContext>
  );
};

export default News;

When i pressed the button, it wont do anything. Any tips?

1 Answer 1

2

You're trying to use context outside the NewsContext component

The solution for this will be to create a component that will call useContext inside NewsContext.

I.e.

const WrappedButton = () => {
  const data = useContext(newsK)

  return <button onClick={data} />
}

And then put it inside the NewsContext:

<NewsContext>
  <div>
    <WrappedButton />
  </div>
</NewsContext>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.